Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 529
kakush Avatar asked Feb 02 '12 10:02

kakush


People also ask

How do you declare a static member variable in C++?

When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.

What is undefined reference?

An “Undefined Reference” error occurs when we have a reference to object name (class, function, variable, etc.) in our program and the linker cannot find its definition when it tries to search for it in all the linked object files and libraries.

What is static member function in C++?

The static member functions are special functions used to access the static data members or other static member functions. A member function is defined using the static keyword. A static member function shares the single copy of the member function to any number of the class' objects.

Why is static member variable not defined inside the class?

Because static member variables are not part of the individual class objects (they are treated similarly to global variables, and get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope.


2 Answers

You need to define _frequency in the .cpp file.

i.e.

LARGE_INTEGER WindowsTimer::_frequency; 
like image 52
Ed Heal Avatar answered Oct 06 '22 02:10

Ed Heal


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; 
like image 42
betteroutthanin Avatar answered Oct 06 '22 00:10

betteroutthanin