C++VS2010链接器关于命名空间变量的错误
C++ VS2010 Linker error regarding namespace variables
MyNamespace.h:
namespace MyNamespace{
int a
}
MyNamespace.cpp:一些使用的函数
main.cpp
#include "MyNamespace.h"
main.obj : error LNK2005: "class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > FileNamespace::m_rootDirectoryPath" (?m_rootDirectoryPath@FileNamespace@@3V?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@A) already defined in FileNamespace.obj 1>main.obj : error LNK2005: "struct FileNamespace::FileTree FileNamespace::m_dataFileTree" (?m_dataFileTree@FileNamespace@@3UFileTree@1@A) already defined in FileNamespace.obj
您在多个翻译单元中定义全局变量(具有外部链接),这会导致重复的定义错误(因为您违反了ODR)。
相反,您应该做的是在标头中用extern
声明声明
namespace MyNamespace{
extern int a;
}
并在单个.cpp文件中定义它(可能在MyNamespace.cpp
中)
int MyNamespace::a;
这样,编译器将在单个对象模块中只创建该变量的一个实例,链接器将把其他对象模块中对该变量的所有引用链接到该实例。
注意到这与在标头中声明函数(只在那里编写原型)和将定义在单个.cpp
中完全等效,这可能有助于您理解问题。
命名空间与其他变量没有什么不同;在标题中,您实际上是在定义"a",而不仅仅是声明它。
在您的标题中:
namespace MyNamespace{
extern int a;
}
在一个源文件中:
int MyNamespace::a;
相关文章:
- 修复未初始化的局部变量错误
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- 如何修复C 中向量的过载变量错误
- GUI QT全局变量错误
- 全局变量错误C
- GetFieldValue用于时间变量错误
- 变量错误:未知类型名称
- 在变量错误中浮动
- 无法使用函数变量?错误表达式必须具有类类型
- 计数器变量错误
- 初始化 cpp 文件中的私有静态成员变量.错误:成员是私有的
- 在 GetTransfer 之后,我在帐户 1 收到未分配变量错误。我无法弄清楚我搞砸了什么逻辑错误
- 变量错误的重新定义
- 在 C++ 中传递 int 变量 - 错误检查不返回值
- 未使用的变量错误,或者应该是错误
- C++外部矢量变量错误
- c模板成员变量错误
- c++中的全局变量错误LNK2020
- vc++类.静态变量错误,外部符号无法解析