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?

99791 次浏览

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

也就是说。

LARGE_INTEGER WindowsTimer::_frequency;

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

更详细的解释 给你

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

LARGE_INTEGER WindowsTimer::_frequency = 0;

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

inline static LARGE_INTEGER _frequency;

这是 另一个问题的完整代码示例,它实际上是这个示例的副本。

#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;
}