Home >Backend Development >C++ >Why Does 'undefined reference to WindowsTimer::_frequency' Occur and How Is It Fixed?

Why Does 'undefined reference to WindowsTimer::_frequency' Occur and How Is It Fixed?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-25 14:21:10270browse

Why Does

Undefined Reference to a Static Member

This error occurs when the compiler cannot find the definition of a static member variable. In this case, it pertains to the static member variable _frequency of the WindowsTimer class.

Understanding the Code

The code presented is:

class WindowsTimer {
public:
  WindowsTimer() {
    _frequency.QuadPart = 0ull;
  }
private:
  static LARGE_INTEGER _frequency;
};

Here, _frequency is a static member variable of type LARGE_INTEGER, which is declared but not defined within the class.

Resolving the Error

The error message "undefined reference to WindowsTimer::_frequency" indicates that the compiler cannot find the definition of _frequency. Static member variables must be defined outside the class declaration, typically in the implementation (.cpp) file.

To resolve the error, add the following definition to the .cpp file:

LARGE_INTEGER WindowsTimer::_frequency;

This will create a global variable of type LARGE_INTEGER named _frequency that is linked to the WindowsTimer class.

Why the Other Changes Didn't Work

  • Changing _frequency to _frequency.QuadPart would only define the QuadPart member of the LARGE_INTEGER struct, but not the _frequency itself.
  • Changing _frequency to static LARGE_INTEGER _frequency.QuadPart would attempt to redefine _frequency as a static variable with type LARGE_INTEGER.QuadPart, which is incorrect.

The above is the detailed content of Why Does 'undefined reference to WindowsTimer::_frequency' Occur and How Is It Fixed?. 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