Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my extern variable initialized yet?

Tags:

c++

extern

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?

like image 816
sholsapp Avatar asked Feb 01 '12 07:02

sholsapp


People also ask

How do you initialize an extern variable?

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.

How do you declare an extern in C++?

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.

Are global variables automatically initialized to 0?

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.

Where is extern variable stored?

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.


2 Answers

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.

like image 116
Martin York Avatar answered Sep 25 '22 16:09

Martin York


From the comp.lang.c++ FAQ, see:

  • [10.14] What's the "static initialization order fiasco"?
  • [10.15] How do I prevent the "static initialization order fiasco"?
like image 21
jamesdlin Avatar answered Sep 25 '22 16:09

jamesdlin