'Undefined reference to a static member

I'm using a cross compiler. My code is:

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

I get the following error:

undefined reference to `WindowsTimer::_frequency'

I also tried to change it to

LARGE_INTEGER _frequency.QuadPart = 0ull;

or

static LARGE_INTEGER _frequency.QuadPart = 0ull;

but I'm still getting errors.

anyone knows why?



Solution 1:[1]

You need to define _frequency in the .cpp file.

i.e.

LARGE_INTEGER WindowsTimer::_frequency;

Solution 2:[2]

With C++17, you can declare your variable inline, no need to define it in a cpp file any more.

inline static LARGE_INTEGER _frequency;

Solution 3:[3]

Linker doesn't know where to allocate data for _frequency and you have to tell it manually. You can achieve this by simple adding this line: LARGE_INTEGER WindowsTimer::_frequency = 0; into one of your C++ sources.

More detailed explanation here

Solution 4:[4]

If there is a static variable declared inside the class then you should define it in the cpp file like this

LARGE_INTEGER WindowsTimer::_frequency = 0;

Solution 5:[5]

This is a full code example for this other question which is indeed a duplicate of this one.

#include <iostream>

#include <vector>
using namespace std;

class Car
{

public:
    static int b;                   // DECLARATION of a static member


    static char* x1(int x)
    {
        b = x;                      // The static member is used "not as a constant value"
                                    //  (it is said ODR used): definition required
        return (char*)"done";
    }

};

int Car::b;                         // DEFINITION of the static 

int main()
{
    char* ret = Car::x1(42);
    for (int x = 0; x < 4; x++)
    {
        cout << ret[x] << endl;
    }

    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ed Heal
Solution 2 betteroutthanin
Solution 3 Community
Solution 4 Raghuram
Solution 5 Serge Ballesta