C++ 对静态成员的未定义引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9110487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:18:20  来源:igfitidea点击:

Undefined reference to a static member

c++undefined-referencecross-compiling

提问by kakush

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'

对“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?

有谁知道为什么?

回答by Ed Heal

You need to define _frequencyin the .cpp file.

您需要_frequency在 .cpp 文件中定义。

i.e.

IE

LARGE_INTEGER WindowsTimer::_frequency;

回答by Vyktor

Linker doesn't know where to allocate data for _frequencyand 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.

链接器不知道将数据分配到哪里_frequency,您必须手动告诉它。您可以通过简单地将这一行添加LARGE_INTEGER WindowsTimer::_frequency = 0;到您的 C++ 源代码中来实现这一点。

More detailed explanation here

更详细的解释在这里

回答by Raghuram

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

如果在类中声明了一个静态变量,那么你应该像这样在 cpp 文件中定义它

LARGE_INTEGER WindowsTimer::_frequency = 0;

回答by Zhenxiao Hao

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

使用 C++17,您可以声明您的变量inline,不再需要在 cpp 文件中定义它。

inline static LARGE_INTEGER _frequency;