This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: constructor calling order

> Date: Sun, 20 Jan 2002 19:45:38 +0100
> From: Alexander Sieb <>
> To:

> 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:

Some_Class  A  __attribute__ ((init_priority (2000)));
Some_Class  B  __attribute__ ((init_priority (543)));
@end example

Note that the particular values of @var{priority} do not matter; only their
relative ordering.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]