静态变量链接错误,C++
Static variable link error, C++
请考虑此代码。
//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;
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'