静态变量链接错误,C++

Static variable link error, C++

本文关键字:C++ 错误 链接 变量 静态      更新时间:2023-10-16

请考虑此代码。

//header.h
int x;
//otherSource.cpp
#include "header.h"
//main.cpp
#include "header.h"
...
int main()
{
}

在这种情况下,编译器错误地处理了消息。"致命错误LNK1169:找到一个或多个多重定义的符号"

但是当我在 x 之前添加静态时,它可以编译而没有错误。

这是第二种情况。

//header.h
class A
{
public:
    void f(){}
    static int a;
};
int A::a = 0;
/otherSource.cpp
#include "header.h"
//main.cpp
#include "header.h"
...
int main()
{
}

在这种情况下,编译器再次错误地使用多个声明。

谁能解释一下我们在类和全局声明中静态变量的行为?提前谢谢。

静态成员变量的问题在于,定义出现在头文件中。 如果在多个源文件中#include该文件,则静态成员变量有多个定义。

要解决此问题,头文件应仅包含以下内容:

#ifndef HEADER_H
#define HEADER_H
// In the header file
class A
{
public:
    void f(){}
    static int a;
};
#endif

静态变量a的定义应该在一个且只有一个模块中。 显而易见的地方是你的main.cpp.

#include "header.h"
int A::a = 0;  // defined here
int main()
{
}

header.h 中将x声明为 extern,以告诉编译器x将在其他地方定义:

extern int x;

然后在您认为最合适的源文件中定义一次x
例如在otherSource.cpp

int x = some_initial_value;