#include #include #include "mydso.h" int foobar=69; int myclass::foo = 69; int myclass::bar = 42; /*#if ((defined __GNUC__) && ( __GNUC__ > 2 ))*/ int _init(void) #if (defined __GNUC__) __attribute__ ((constructor)) #endif ; int _init(void) { printf("_init called\n"); } static myinitclass initdso; /* * in "initdso" constructor we will try to set "myclass::bar" to "-1" * * static dynamic ($CXX) dynamic(ld) * compiler * IRIX Mips Pro 7.x CC + * - * IRIX g++ 2.95.2 * * - * Linux g++ 2.96 * * - * Linux icc 2.96 * * - * SunOS 2.8 g++ 2.96 * * - * SunOS 2.8 CC 5.x + * - * Tru64 Compaq C V6.1 * * * * Darwin gcc + + + * * [-] -> initdso is not called * [+] -> initdso is called after constructor * [*] -> initdso is called, but init() overrides. */ /* SEE ALSO: * [10.9] What's the "static initialization order fiasco"? * http://users.utu.fi/sisasa/oasis/cppfaq/ctors.html#[10.7] */ void myclass::init() { // "s" can not be initialized here, since it's non static. // we will initialize it in main.cc // s="Hello, World\n"; // Next line would make linker fail: Unresolved data symbol "myclass::bar" // unless "myclass::bar" has been initialized previously. bar=43; fprintf(stderr,"myinitclass constructor\n"); /* foo = 70;*/ } myclass::myclass() { init(); } /* Since constructors are called for each new object of a class, static data members are never initialized by constructors. At most they are modified. The reason for this is that the static data members exist before the constructor of the class is called for the very first time. The static data members can be initialized during their definition, outside of all member functions, in the same way as global variables are initialized. The definition and initialization of a static data member usually occurs in one of the source files of the class functions, preferably in a source file dedicated to the definition of static data members, called data.cc. */ myinitclass::myinitclass() { myclass::bar=-1; fprintf(stderr,"myinitclass called\n"); } /***************************************************************************/ int mygoodclass::foo = 69; int& mygoodclass::bar() { static int barinited=0; static int* ans= new int(); if ( barinited == 0 ) { *ans=-1; barinited = 1; fprintf(stderr,"myinitgoodclass inited\n"); } fprintf(stderr,"myinitgoodclass called 0x%p\n", ans); return *ans; } void mygoodclass::init() { } mygoodclass::mygoodclass() { init(); }