【发布时间】:2017-05-05 15:19:35
【问题描述】:
考虑以下场景:
MyFile.cpp:
const int myVar = 0; // 全局变量
另一个文件.cpp:
void myFun()
{
std::cout << myVar; // compiler error: Undefined symbol
}
现在如果我在使用之前在 AnotherFile.cpp 中添加extern const int myVar;,链接器会报错为
未解决的外部
我可以将myVar 的声明移动到MyFile.h 并在AnotherFile.cpp 中包含MyFile.h 来解决问题.但我不想将声明移至头文件。我还有其他方法可以完成这项工作吗?
【问题讨论】: