How can I avoid the LNK2005 linker error for variables defined in a header file?(对于头文件中定义的变量,如何避免 LNK2005 链接器错误?)
问题描述
我有 3 个类似这样的 cpp 文件
I have 3 cpp files that look like this
#include "Variables.h"
void AppMain() {
//Stuff...
}
它们都在其中使用相同的变量,因此它们具有相同的标题,但我得到了这样的东西
They all use the same variables inside them so they have the same headers but I get stuff like this
1>OnTimer.obj : error LNK2005: "int slider" (?slider@@3HA) already defined in AppMain.obj
这是为什么呢?
推荐答案
请记住,#include 大致类似于在包含它的源文件中剪切和粘贴包含文件(这是一个粗略的类比,但你会得到点).这意味着如果您有:
Keep in mind that a #include is roughly like cutting and pasting the included file inside the source file that includes it (this is a rough analogy, but you get the point). That means if you have:
int x; // or "slider" or whatever vars are conflicting
在头文件中,并且该头文件被程序中的三个源文件包含,那么它们都将定义一个名为 x 的全局名称,这将发生冲突.
in the header file and that header file is included by three source files in a program, then they will all have a global named x defined that will conflict.
您要做的是将变量定义为 extern,以便 .cpp 文件都获得声明,然后在您的一个 .cpp 文件中给出实际定义.
What you want to do is define the variable as extern so that the .cpp files will all get the declaration, and then in ONE of your .cpp files give the actual definition.
在变量.h 中:
extern int x;
在 SomeSourceFile.cpp 中
in SomeSourceFile.cpp
int x;
当然,我建议不要使用全局变量,但如果您必须使用它们,这将避免它们发生冲突.
Of course, I'd recommend against globals, but if you must use them this would keep them from conflicting.
这篇关于对于头文件中定义的变量,如何避免 LNK2005 链接器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对于头文件中定义的变量,如何避免 LNK2005 链接器错误?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01