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

时间:2017-05-05 06:48:32

标签: c++ extern

考虑以下情况:

MYFILE.CPP

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

AnotherFile.cpp

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

现在,如果我在使用之前在 AnotherFile.cpp 中添加extern const int myVar;,链接器就会抱怨

  

未解决的外部

我可以将myVar的声明移到 MyFile.h 并在 AnotherFile.cpp 中包含 MyFile.h 来解决问题。但我不想将声明移到头文件中。还有其他方法可以让我的工作吗?

1 个答案:

答案 0 :(得分:3)

在C ++中,const implies internal linkage。您需要在MyFile.cpp中声明myVarextern

extern const int myVar = 0;

在AnotherFile.cpp中:

extern const int myVar;
相关问题