Search code examples
c++extern

Accessing 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 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?


Solution

  • 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;