Undefined Reference to a Static Member: Resolving Compilation Issues
When working with static members in C , particularly while using a cross compiler, you may encounter the error "undefined reference to a static member." This error occurs due to the lack of a definition for a static member variable in a source file. To resolve this issue, follow these steps:
Understanding the Issue
In your example, you have defined a static member variable _frequency within the class WindowsTimer. However, you have not defined its actual data in a separate source file (.cpp file). This is the root cause of the compilation error.
Solution: Defining Static Members
To fix the error, define the static member variable in a separate source file, typically a .cpp file. For example:
// WindowsTimer.cpp LARGE_INTEGER WindowsTimer::_frequency;
This definition allocates memory for the static variable and allows the compiler to reference it during the linking stage.
Why External Definition is Necessary
When working with static members, it's important to understand that their definition must be external to the class declaration. This is because the compiler requires the full definition of a static member before generating the code and linking the object files.
Avoid Placing Definitions in Header Files
While it's tempting to define static members inside header files (.h files) for ease of access, it's not a good practice. Multiple inclusions of the header file can lead to multiple definitions of the static variable, resulting in linker errors or undefined behavior.
The above is the detailed content of Undefined Reference to Static Member in C : How to Resolve Compilation Issues?. For more information, please follow other related articles on the PHP Chinese website!