-
Globals initialization
I have a question about the initialization of global variables:
If I define in one .cpp-file "int a = 12" and then declare in the .cpp-file with the main function "extern int a", is it guaranteed by c++-standard that "int a" was initialized before entering main()? Or could it happen that "int a" is initialized with 0 at use, because the statics initialization of the other cpp-file wasn't executed?
The global is always correctly initialized across several files with my compiler (gcc), but I'd like to know if it's defined to happen that way.
And yes, I know that globals are evil. ;)
-
The only guarantee you have is that the global will be initialized before it's first use. However, most implementations will initialize all globals before main() is called.
Google-Groups("C C++ global initialization")
Look in comp.lang.c.moderated and comp.lang.c++.moderated.
gg
-
I think it's strange that people have been already complaining about this in 1993 and it was never changed. That the problem of dependencies among those definitions might be hard to solve is understandable, but at least the initialization of all globals in all files before entering main could be required by the standard.
-
New++, the initialization of globals in a single translation unit, ie., a .cpp file with all the defines preprocessed, is defined, the globals defined first are initialized first. (You can always depend on the 0 initialization.) But for globals spanning multiple files, the initialization order is undefined, usually depending on the order of the files given to the linker, meaning even if the C++ standard defined an initialization order, the order of initialization would be useless for practical purposes. Further, there are easy to use techniques using a function like
Code:
int getI()
{
static int i = 4;
return i;
}
When this function is called, even from a global context, the variable i is automatically initialized.