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

Cin*_*out 1 c++ extern

考虑以下场景:

我的文件.cpp :

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

另一个文件.cpp

void myFun()
{
    std::cout << myVar; // compiler error: Undefined symbol
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我添加extern const int myVar;AnotherFile.cpp使用前,连接器作为抱怨

未解决的外部

我可以移动的声明myVar,以MyFile.h,包括MyFile.hAnotherFile.cpp来解决这个问题。但我不想将声明移动到头文件中。有没有其他方法可以使这项工作?

the*_*rge 5

在 C++ 中,const 意味着内部链接。需要声明myVarextern在MYFILE.CPP:

extern const int myVar = 0;
Run Code Online (Sandbox Code Playgroud)

在 AnotherFile.cpp 中:

extern const int myVar;
Run Code Online (Sandbox Code Playgroud)