Access to a global variable defined in a .cpp file in another .cpp file

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 use, the linker complains how

Unauthorized External

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

+1
source share
1 answer

In C ++ const , internal binding is implied . You need to declare myVar as extern in MyFile.cpp:

 extern const int myVar = 0; 

In AnotherFile.cpp:

 extern const int myVar; 
+3
source

Source: https://habr.com/ru/post/1432589/


All Articles