Undefined reference to a static member

2019-01-03 10:19发布

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?

4条回答
来,给爷笑一个
2楼-- · 2019-01-03 10:28

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;
查看更多
太酷不给撩
3楼-- · 2019-01-03 10:32

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

查看更多
爷的心禁止访问
4楼-- · 2019-01-03 10:47

You need to define _frequency in the .cpp file.

i.e.

LARGE_INTEGER WindowsTimer::_frequency;
查看更多
可以哭但决不认输i
5楼-- · 2019-01-03 10:49

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;
查看更多
登录 后发表回答