The test code #include <stdlib.h> class Test { public: int t; Test():t(1) {} }; Test ex_t; void Init() __attribute__ ((constructor)); void Init() { if(ex_t.t==0) abort(); } int main(void) { return 0; } aborted if compiled with gcc 4.3.2. If compiled with gcc 4.1.0 or 3.3.6 it proceed normally. As I understand, in first case the ex_t constructor called after function Init, but in second case the ex_t constructor called before function Init. I not found in documentation what case is right, so I think this is a bug. In my opinion, constructors of global variables must have more priority than __attribute__ ((constructor)) functions. Compilation command is simple: g++ -o test test.cpp
This works on the trunk at -O0 but fails at -O2. I think this is undefined as the priority are the same. You should use init_priority and set a priority for the constructor.
The priority must not be same. The only method to interact constructor function with main is global variables. It is no reason to initialize global variables after constructor function. Anyway, Test ex_t __attribute__ ((init_priority(102))); void Init() __attribute__ ((constructor(101))); have no effect.
(In reply to Michael Uleysky from comment #2) > The priority must not be same. The only method to interact constructor > function with main is global variables. It is no reason to initialize global > variables after constructor function. Anyway, > > Test ex_t __attribute__ ((init_priority(102))); > void Init() __attribute__ ((constructor(101))); Because you have the wrong order, lower number is a higher priority which means 101/Init will always be first. From https://gcc.gnu.org/onlinedocs/gcc-11.2.0/gcc/Common-Function-Attributes.html#index-constructor-function-attribute: "However, at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute constructor are invoked is unspecified. In mixed declarations, attribute init_priority can be used to impose a specific ordering." "A constructor with a smaller priority number runs before a constructor with a larger priority"