Example:
struct Foo { Foo() { printf("foo\n"); } };
static Foo foo;
__attribute__((constructor)) static void _bar() { printf("bar\n"); }
Is it deterministic wether foo or bar is printed first?
(I hope and would expect that constructors of static objects are always executed first but not sure and GCCs doc about the constructor attribute doesn’t say anything about it.)
foowill be printed first, as the objects are initialized in the order of their declarations. Run and see:By the way,
__attribute__((constructor))is not Standard C++. It is GCC’s extension. So the behavior of your program depends on how GCC has defined it. In short, it is implementation-defined, according to itfoois printed first.The doc says,
I think the text in bold implies, the objects are initialized in the order of their declarations, as I said before, which is pretty much confirmed by online demo also.
I guess you would also like to read this:
If you want to control/alter the initialization order, you can use
init_priorityattribute, providing priority. Taken from the page:Here,
Bis initialized beforeA.