考虑以下场景:
我的文件.cpp:
const int myVar = 0;
// 全局变量
另一个文件.cpp:
void myFun()
{
std::cout << myVar; // compiler error: Undefined symbol
}
现在如果我添加extern const int myVar;
in 另一个文件.cpp在使用之前,链接器抱怨为
未解决的外部
我可以移动声明myVar
to MyFile.h并包括MyFile.h in 另一个文件.cpp来解决问题。但我不想将声明移至头文件中。我还有其他方法可以完成这项工作吗?
In C++, const
暗示内部联系 https://stackoverflow.com/questions/998425/why-does-const-imply-internal-linkage-in-c-when-it-doesnt-in-c。您需要声明myVar
as extern
在 MyFile.cpp 中:
extern const int myVar = 0;
AnotherFile.cpp 中的:
extern const int myVar;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)