Home >Backend Development >C++ >Why Do I Get 'Undefined Reference to Static Member' Errors During Cross Compilation?
Unresolved Reference to a Static Member in Cross Compilation
When working with cross compilers, it's common to encounter errors related to unresolved references to static members. This occurs when a static variable is declared in a class header but not defined in the corresponding .cpp file.
Problem Explanation:
Consider the provided code example:
class WindowsTimer { public: WindowsTimer() { _frequency.QuadPart = 0ull; } private: static LARGE_INTEGER _frequency; };
The static variable _frequency is declared within the class definition but is not defined. When attempting to build the code, the linker fails to resolve the reference to _frequency, resulting in an undefined reference error.
Solution:
To resolve this issue, the static variable must be defined in the corresponding .cpp file. This can be done as follows:
// WindowsTimer.cpp LARGE_INTEGER WindowsTimer::_frequency;
Reasoning:
Static variables, unlike instance variables, are shared among all instances of a class. Therefore, they require a single definition in the program. By defining the static variable in the .cpp file, the linker can successfully locate and resolve the reference to it.
Additional Notes:
The above is the detailed content of Why Do I Get 'Undefined Reference to Static Member' Errors During Cross Compilation?. For more information, please follow other related articles on the PHP Chinese website!