如何避免在头文件中定义的变量的LNK2005链接器错误? [英] How can I avoid the LNK2005 linker error for variables defined in a header file?
问题描述
我有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
/ p>
Why is that?
推荐答案
请记住,#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.
在Variables.h中:
in Variables.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链接器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!