/* * This file is the source for a DSO * * This DSO will include an static class "initdso" */ #include #include #include "mydso.h" int global_static_int=69; int myclass::foo = 69; int myclass::bar = 42; /* * GCC METHOD: * * gcc will call "__attribute__ ((constructor))" funcions on loading dso */ int my_init(void) #if (defined __GNUC__) __attribute__ ((constructor)) #endif ; /* with this setup "my_init" is called two times ?! */ int my_init(void) { printf("my_init called\n"); return 0; } /* gcc defaults to call "_init" also * In g++ it seems _init is not called. * I guess it's a name mangling issue. */ int _init(void) { printf("_init called\n"); return 0; } static myinitclass initdso; /* * in "initdso" constructor we will try to set "myclass::bar" to "-1" * * static dynamic dynamic _init my_init * ($CXX) (ld) * compiler * IRIX Mips Pro 7.x CC + * - 0 - * IRIX g++ 2.95.2 * * - 0 1 * Linux g++ 2.96 * * - 0 2 * Linux icc 2.96 * * - 0 0 * SunOS 2.8 g++ 2.96 * * - 0 1 * SunOS 2.8 CC 5.x + * - * SunOS 2.8 CC 6.x + * - 0 0 * 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(); }