2

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?

CinCout
  • 9,486
  • 12
  • 49
  • 67

1 Answers1

6

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;
Community
  • 1
  • 1
themiurge
  • 1,619
  • 17
  • 21