访问在另一个.cpp文件

问题描述:

考虑以下情形中一个.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来解决问题。但我不想将声明移动到头文件中。有什么其他的方式可以使这项工作?

在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