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 initialize any object with the extern storage class specifier at global scope in C or at namespace scope in C++. The initializer for an extern object must either: Appear as part of the definition and the initial value must be described by a constant expression; or.
The “extern” keyword is used to declare and define the external variables. The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.
Yes, all members of a are guaranteed to be initialised to 0. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
extern variables are stored in the data segment. The extern modifier tells the compiler that a different compilation unit is actually declaring the variable, so don't create another instance of it or there will be a name collision at link time.
You can't (in a consistent manner)
But you can work around it.
global.cpp
// If you have a global variable that has to be initial by a constructor
MyObj globalX;
// Instead do this
MyObj& globalX() { static MyObj x; return x;}
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.
From the comp.lang.c++ FAQ, see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With