Home >Backend Development >C++ >Why Do I Get 'Undefined Reference to Static Member' Errors During Cross Compilation?

Why Do I Get 'Undefined Reference to Static Member' Errors During Cross Compilation?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 20:46:10606browse

Why Do I Get

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 error message "undefined reference to WindowsTimer::_frequency'" explicitly indicates that the linker is unable to find a definition for the variable _frequency in the context of the class WindowsTimer`.
  • Modifying the declaration of _frequency as LARGE_INTEGER _frequency.QuadPart = 0ull; or static LARGE_INTEGER _frequency.QuadPart = 0ull; will not solve the issue, as these declarations only apply to the individual instance of _frequency within the object and not to the static definition.
  • It's important to ensure that the definition of the static variable in the .cpp file matches the declaration in the header file. Mismatches can lead to unexpected behavior or compilation errors.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn