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

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

本文关键字:文件 cpp 全局变量 定义 另一个 访问      更新时间:2023-10-16

考虑以下方案:

myfile.cpp

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

另一个file.cpp

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

现在,如果我在 emotefile.cpp中添加 extern const int myVar;

未解决的外部

我可以将 myVar的声明移至 myfile.h ,并include myfile.h in eme> ernefile.cpp 以解决问题。但是我不想将声明移至标题文件。还有其他方法可以做这项工作吗?

在C 中,const意味着内部链接。您需要在myfile.cpp中将 myVar声明为 extern

extern const int myVar = 0;

在另一个file.cpp中:

extern const int myVar;