Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How lazy can C++ global initialization be?

I'm used to thinking of all initialization of globals/static-class-members as happening before the first line of main(). But I recently read somewhere that the standard allows initialization to happen later to "assist with dynamic loading of modules." I could see this being true when dynamic linking: I wouldn't expect a global initialized in a library to be initialized before I dlopen'ed the library. However, within a grouping of statically linked together translation units (my app's direct .o files) I would find this behavior very unintuitive. Does this only happen lazily when dynamically linking or can it happen at any time? (or was what I read just wrong? ;)

like image 375
Joseph Garvin Avatar asked Aug 06 '09 14:08

Joseph Garvin


People also ask

Can global variables be initialized in C?

In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.

Are global structs initialized to 0?

Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).

Are global variables slow in C?

Global variables are really slow, in addition to all the other reasons not to use them.

What is the value of uninitialized global variable in C?

Global variables get there space in the data segment which is zeroed out. It is not compiler specific but defined in the C standard. So it will always print 0.


1 Answers

The standard has the following in 3.6.2/3:

It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.

But o Of course you can never officially tell when the initialization takes place since the initialization will occur before you access the variable! as follows:

// t1.cc
#include <iostream>
int i1 = 0;

int main () {
  std::cout << i1 << std::endl

// t2.cc
extern int i1;
int i2 = ++i1;

I can conform that g++ 4.2.4 at least appears to perform the initialization of 'i2' before main.

like image 61
Richard Corden Avatar answered Sep 26 '22 22:09

Richard Corden