My question pertains to the order of initialization of global objects. It is discussed to some extent here: C++: When (and how) are C++ Global Static Constructors Called?
What I would like to know is, how is it guaranteed that some system library objects (can’t think of an example though) are initialized before they are used in application? (I know the solution is to wrap such object in a function, but I want to understand how it is dealt in compilers today)
This is also discussed in the book “linkers and loaders” by John Levine, while talking about .init and .finit sections, but the current state of art is not clear.
An example would be
cout.The compiler doesn’t really guarantee that those objects are built before they are used. Take this code:
It segfaults because the foo object gets built before cout. When it tries to use cout, bad things happen.
Basically, all the global objects will get code inserted to construct them which runs before main. Once you are in main you are safe, all objects are built. Before that it depends on the order in which they are defined. That’s why I can break it by including iostream after declaring the foo global.