I’m compiling a shared library with two compilation units: globals.cpp and stuff.cpp. The globals.cpp file initializes a handful of extern variables that are used in stuff.cpp. The issue I’m experiencing is that the code in stuff.cpp is running before the code in globals.cpp has had the opportunity to assign a value to the extern variables. E.g., I’m seeing a bunch of 0 values being used. This issue depends on what platform I compile/run the code on — some work and some do not.
How does one go about resolving this? Can I force globals.cpp to run first?
You can’t (in a consistent manner)
But you can work around it.
global.cpp
You still have a global variable. But by putting it in a function we know when it is being used. By using a static member of the function it is initialized the first time the function is called but not after that. Thus you know that it will be correctly constructed before first use.