Search code examples
c++undefinedextern

Extern variable undefined


I am facing a problem with extern variable declaration. I have a bunch of .cpp files containing definitions of structs:

const System SystemA = {"A", 1, 2 ...}; //In A.cpp
const System SystemB = {"B", 1, 2 ...}; //In B.cpp
...

These Cpp files are just to server as a simple way to add new structs, and to look for one specific struct definition easily. (since I may have 100 definitions, and each of them is multiple [50] lines of code).

When I try to use them in another compilation unit (.cpp):

extern const System SystemA;
extern const System SystemB;
...

void InitStructs(){
    SystemA.Init();
    SystemB.Init();
    ...
}

I just get undefined reference to SystemA undefined reference to SystemB, and so on. I am doing this unified initialization, because I was doing the initialization as a static dynamic initialization in each system.cpp. But that is risky since the order of initialization is not ensured (static initialization order fiasco). Therefore I was getting segmentation faults depending on the cpp compilation order.

I moved towards this approach, but now it doesn even compile.... Any help?


Solution

  • In C++, const objects at global scope are by default also static, i.e., they are not visible outside the source file. To fix that, add extern to each of the definitions.