Accessing a global variable defined in a .cpp file in another .cpp file [duplicate]

断了今生、忘了曾经 提交于 2019-12-11 06:15:17

问题


Consider the following scenario:

MyFile.cpp:

const int myVar = 0; // global variable

AnotherFile.cpp:

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

Now if I add extern const int myVar; in AnotherFile.cpp before using, linker complains as

Unresolved external

I can move the declaration of myVar to MyFile.h and include MyFile.h in AnotherFile.cpp to solve the issue. But I do not want to move the declaration to the header file. Is there any other way I can make this work?


回答1:


In C++, const implies internal linkage. You need to declare myVar as extern in MyFile.cpp:

extern const int myVar = 0;

The in AnotherFile.cpp:

extern const int myVar;


来源:https://stackoverflow.com/questions/43798283/accessing-a-global-variable-defined-in-a-cpp-file-in-another-cpp-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!