ordering of constructors

Neal Becker ndbecker2@verizon.net
Sun Apr 11 12:03:00 GMT 2004


Gabriel Dos Reis wrote:

> Neal Becker <ndbecker2@verizon.net> writes:
> 
> | Thanks for all the interesting responses to my question.  Am I correct
> | to summarize that there is currently no simple way to guarantee ordering
> | of
> | global constructors?  (A couple of methods were suggested, but if I
> | understand correctly, none are guaranteed to work?)
> 
> There probably is no *general* method guaranteed to work.  However,
> you may want to look at your specific example whether it contains the
> problematic cases raised in this thread.
> Note that this is an issue only when you really have a dynamic
> initialization.
> 

By "dynamic initialization", do you mean there is an issue only for global
constructors in shared libs?

AFAICT, there is a problem even without considering shared libs.  I tried
what you suggested, I think, and it doesn't seem to work.

#A.H:
struct A {
  A() : x (2) {
    std::clog << "A():\n";
    //    print_trace();
  }
  int x;
} ;

extern A a;
void make_sure_a_is_constructed();

#A.cc:
include "A.H"

A a __attribute__((init_priority (1000)));

void make_sure_a_is_constructed() {
  std::clog << "make_sure_a_is_constructed():\n";
  //  print_trace();
}

#B.H:
#include "A.H"
//#include "Trace.H"

struct B {
  B() {
    std::clog << "B():\n";
    //    print_trace();
    make_sure_a_is_constructed();
    std::clog << "A.x: " << a.x << '\n';
  }
};

#B.cc:
#include "B.H"

B b __attribute__((init_priority(1001)));

#Test1.cc:
#include "A.H"
#include "B.H"


int main() {
  return 0;
}

Remove the init_priority attributes, and it will print a a value of 0 for
A.x, instead of the correct value of 2.

At least, that's what I got using
g++ -g -rdynamic -o Test1 Test1.cc A.cc B.cc


[nbecker@localhost cln]$ gcc -v
Reading specs from /usr/lib/gcc-lib/x86_64-redhat-linux/3.3.3/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --enable-shared --enable-threads=posix
--disable-checking --disable-libunwind-exceptions --with-system-zlib
--enable-__cxa_atexit --host=x86_64-redhat-linux
Thread model: posix
gcc version 3.3.3 20040311 (Red Hat Linux 3.3.3-3)



More information about the Gcc mailing list