我需要在 Visual Studio 项目的多个 cpp 文件中编辑和访问一些变量。所以我创建了一个头文件,它的命名空间包含我需要的所有变量,如下所示:
namespace windowdimension{
TCHAR openwindows[20][180];
int winnum = 0;
int windowleft = 0;
int windowright = 1360;
INT windowtop = 0;
INT windowbottom = 768;
LONG leftarray[20];
LONG rightarray[20];
LONG toparray[20];
LONG bottomarray[20];
}
但是,如果我在两个源文件中#include
这个头文件,我会得到这个链接器错误 2005,说参数已经在另一个 obj 中定义了。
引用同样错误的其他问题,我知道了here那个
a function definition can only appear once. Every .cpp file that #includes your .h file will generate yet another copy of the function.
但这也适用于命名空间变量吗? 如果是这样,我们如何确保跨多个源文件访问特定变量?
最佳答案
永远不要在头文件中定义全局变量。
为了能够共享,您需要在头文件中声明它们(使用 extern
关键字),并且在 .cpp 文件中只定义一次。
当然,永远不要忘记在每个头文件中包含保护(#pragma once
是非常便携的解决方案):
全局.hpp
#pragma once
namespace global {
extern int variable;
}
全局.cpp
namespace global {
int variable = 0;
}
无论如何,使用全局变量是一种非常糟糕的做法。
关于c++ - 错误 LNK2005 : already defined on including a header file twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015597/