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
Undefined reference to a static member
提问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 _frequency
in the .cpp file.
您需要_frequency
在 .cpp 文件中定义。
i.e.
IE
LARGE_INTEGER WindowsTimer::_frequency;
回答by Vyktor
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.
链接器不知道将数据分配到哪里_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;