gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:27:59 26 4
gpt4 key购买 nike

考虑这段代码。

//header.h
int x;

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

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

}

在这种情况下,编译器出错了。 “ fatal error LNK1169:找到一个或多个多重定义的符号”

但是当我在 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()
{

}

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

任何人都可以向我解释我们在类和全局声明中的静态变量的行为吗?提前致谢。

最佳答案

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

关于c++ - 静态变量链接错误,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com