Order of initialization of global/static variables

Jonathan Wakely jwakely.gcc@gmail.com
Wed Apr 30 11:46:00 GMT 2014


On 30 April 2014 01:30, Ian Lance Taylor wrote:
> On Tue, Apr 29, 2014 at 8:08 PM, Yaron Dayagi <yarondayagi@gmail.com> wrote:
>>
>> In gcc 4.4.6 we had no problem with the order of initialization.
>> In gcc 4.7.2 we do have a problem.
>> A CPP file defined GlobalObj_1 (declared extern in the H file):
>> CMyClass GlobalObj_1.
>> Another CPP file declared GlobalObj_2 (also declared extern in the H
>> file).=  The CPP file used copy constructor:
>> CMyClass GlobalObj_2(GlobalObj_1).
>> In 4.4.6 GlobalObj_1 was initialized first. Now GlobalObj_2 is
>> initialized = first.
>> Is this intentional?
>> How do I revert to old behavior?
>> The problem is that we have many files with many global variables (const).
>
> The C++ language does not define the order in which global variables
> in different files are initialized.  Any such dependency in your
> program is a potential bug.
>
> That said, yes, GCC 4.7 did change the order.  See
> http://gcc.gnu.org/PR46770 .  You may be able to change back by
> configuring with --disable-initfini-array.  That said, this solution
> is likely to be only temporary.  The only permanent fix will be to
> remove the unsupported dependency in your C++ program.

Another option is the init_priority attribute documented at
http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html



More information about the Gcc-help mailing list