静态变量 link 错误,C++

Static variable link error, C++

考虑这段代码。

//header.h
int x;

//otherSource.cpp
#include "header.h"

//main.cpp
#include "header.h"
...
int main()
{

}

在这种情况下,编译器因消息而出错。 "fatal error LNK1169: one or more multiply defined symbols found"

但是当我在 x 之前添加 static 时,它编译没有错误。

这里是第二种情况。

//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()
{

}

在这种情况下,编译器再次因多重声明而出错。

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

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

extern int x;

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

int x = some_initial_value;

静态成员变量的问题是您在头文件中进行了定义。如果你#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()
{
}