1
考慮以下情形中一個.cpp文件中定義的全局變量:訪問在另一個.cpp文件
MYFILE.CPP:
const int myVar = 0;
//全局變量
AnotherFile.cpp:
void myFun()
{
std::cout << myVar; // compiler error: Undefined symbol
}
現在,如果我加extern const int myVar;
在AnotherFile.cpp使用前,連接抱怨作爲
無法解析的外部
我可以在AnotherFile的myVar
聲明移到MyFile.h和包括MyFile.h .cpp來解決問題。但我不想將聲明移動到頭文件中。有什麼其他的方式可以使這項工作?
沒有,只是不停地編譯和鏈接之前。 – themiurge
您可以發佈您使用的命令嗎? – themiurge
對不起,我以爲你已經在AnotherFile.cpp中聲明瞭它。你需要把它放在AnotherFile.cpp中:'extern const int myVar;' – themiurge