在另一个 .cpp 文件中访问一个 .cpp 文件中定义的全局变量

Accessing a global variable defined in a .cpp file in another .cpp file

考虑以下场景:

MyFile.cpp:

const int myVar = 0; // 全局变量

AnotherFile.cpp:

void myFun()
{
    std::cout << myVar; // compiler error: Undefined symbol
}

现在,如果我在使用前在 AnotherFile.cpp 中添加 extern const int myVar;,链接器会报错为

Unresolved external

我可以将 myVar 的声明移动到 MyFile.h 并将 MyFile.h 包含在AnotherFile.cpp 解决问题。但是我不想将声明移动到头文件中。我还有其他方法可以完成这项工作吗?

在 C++ 中,const implies internal linkage。您需要在 MyFile.cpp:

中将 myVar 声明为 extern
extern const int myVar = 0;

AnotherFile.cpp中的:

extern const int myVar;