This is the mail archive of the crossgcc@sources.redhat.com mailing list for the crossgcc project.

See the CrossGCC FAQ for lots more information.


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

Re: C++ constructors


Hi,

As others have said, the STANDARD does not specify the order for global
constructors, except for objects within a single compilation unit. You may
be able to do something in a non-standard way, or alternatively collects
the globals into one compilation unit - where they will be constructed in
order (maybe by defining a special macro, and then including all the
header files - which use the macro to know to define storage).

A different approach is to delay construction until first use, this will
solve almost all ordering problems (except loops), at the cost of a
function call+if overhead:-


// Header
class Fred { ....};
Fred *fed_gp();

// fred.cc
Fred *fred_gp()
{
// C++ will only construct fred_s the first time fred_gp is called.
// There is effectively an invisible if here.
static Fred fred_s;
return &fred_s;
}

// user.cc
fred_gp()->method();

Note you can NOT safely declare fred_gp as inline (due to compiler
bugs). Also a static inside a class definition won't work (gets
constructed at global construction time, not when the first method is called).

Cheers
Mark



On Wed, 16 May 2001, [iso-8859-1] Joćo Cadamuro Junior wrote:

> Hello,
>
> I have worked with GCC and G++ for "powerpc-eabi" embedded targets. In
> the last two versions of GCC (2.95.2 and 2.95.3) I have learned some
> hard things about C++ constructor and GCC.
>
> Under gcc-2.95.2 the execution order of constructors is the linkage
> order. The first file linked will construct their objects first.
>
> Under gcc-2.95.3, the behavior is the opposite. The last linked archive
> will construct their objects first.
>
> Since I want to have a c++ code to be compiled correctly independent of
> the compiler version, someone knows what can I do to force some order to
> constructors under G++?
>
>
> Thanks in advance,
>
> Joćo Cadamuro Junior
> LIT / CPDTT / CEFET-PR
>
>
> ------
> Want more information?  See the CrossGCC FAQ, http://www.objsw.com/CrossGCC/
> Want to unsubscribe? Send a note to crossgcc-unsubscribe@sourceware.cygnus.com
>

-- 
Mark S. Phillips        	ESN 742 2461
msp@nortelnetwork.co.uk        	Tel. +44 1279 402461
Nortel Networks plc, London Road, Harlow, Essex, CM17 9NA
[Co #3937799, Registered office address: Maidenhead Office Park,
Westacott Way, Maidenhead, Berkshire SL6 3QH.]



------
Want more information?  See the CrossGCC FAQ, http://www.objsw.com/CrossGCC/
Want to unsubscribe? Send a note to crossgcc-unsubscribe@sourceware.cygnus.com


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