2017-05-05 69 views
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來解決問題。但我不想將聲明移動到頭文件中。有什麼其他的方式可以使這項工作?

回答

3

在C++中,constimplies internal linkage。您需要MYFILE.CPP聲明myVarextern

extern const int myVar = 0; 

中AnotherFile.cpp:

extern const int myVar; 
+0

沒有,只是不停地編譯和鏈接之前。 – themiurge

+0

您可以發佈您使用的命令嗎? – themiurge

+0

對不起,我以爲你已經在AnotherFile.cpp中聲明瞭它。你需要把它放在AnotherFile.cpp中:'extern const int myVar;' – themiurge