This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: constructor calling order
- From: mike stump <mrs at windriver dot com>
- To: alex at rnd dot org, harsha at vishvakannada dot com
- Cc: gcc at gcc dot gnu dot org
- Date: Mon, 21 Jan 2002 12:59:01 -0800 (PST)
- Subject: Re: constructor calling order
> Date: Sun, 20 Jan 2002 19:45:38 +0100
> From: Alexander Sieb <alex@rnd.org>
> To: harsha@vishvakannada.com
> harsha@vishvakannada.com wrote:
> >
> > I have a problem with my program compiled using gcc in linux. In
> > windows same code works fine. I have two cpp files having to
> > global objects of two different classes I want to know which
> > constructor is get called first ? how can I change the order ?
> The initialization order of statics and global variables between
> compilation units is undefined. So you can't change the order of
> initialiation of these objects in portable manner. It's also a good
> practice to minimize the use of global and static objects in
> general. If you have to use them be very careful with respect to
> their order of initialization.
>From the manual:
@table @code
@item init_priority (@var{priority})
@cindex init_priority attribute
In Standard C++, objects defined at namespace scope are guaranteed to be
initialized in an order in strict accordance with that of their definitions
@emph{in a given translation unit}. No guarantee is made for initializations
across translation units. However, GNU C++ allows users to control the
order of initialization of objects defined at namespace scope with the
@code{init_priority} attribute by specifying a relative @var{priority},
a constant integral expression currently bounded between 101 and 65535
inclusive. Lower numbers indicate a higher priority.
In the following example, @code{A} would normally be created before
@code{B}, but the @code{init_priority} attribute has reversed that order:
@example
Some_Class A __attribute__ ((init_priority (2000)));
Some_Class B __attribute__ ((init_priority (543)));
@end example
@noindent
Note that the particular values of @var{priority} do not matter; only their
relative ordering.