对于头文件中定义的变量,如何避免 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.
相关文章