/* Portable constructors in C * * - Supports: GCC, MSVC * * Author: David Zeuthen */ #include #if defined (__GNUC__) /* on the GNU C compiler, this is easy as pie */ #define XXX_CONSTRUCTOR(func) \ static void __attribute ((constructor)) func (void); #elif defined (_MSC_VER) /* From http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c6945__2/ * http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/7737e56f-c813-4c96-a632-5db7a26ef2fc/ * * According to codesearch, the Boost threading library depends on * this.. so it's safe for us to depend on it too. */ #define XXX_CONSTRUCTOR(func) \ static void func (void); \ static int \ constructor_##func (void) \ { \ func (); \ return 0; \ } \ __pragma(section(".CRT$XIU", long, read)) \ __pragma(data_seg(".CRT$XIU")) \ volatile static int(*constructor_ptr_##func) (void) = constructor_##func; \ __pragma(data_seg()) #else #error "Please add constructor/destructor support for your compiler" #endif XXX_CONSTRUCTOR (foo_constructor); XXX_CONSTRUCTOR (bar_constructor); static void foo_constructor (void) { printf ("Hello World from foo_constructor()\n"); } static void bar_constructor (void) { printf ("Hello World from bar_constructor()\n"); } int main (int argc, char *argv[]) { int class = 42; /* this demonstrates this is C, not C++ */ printf ("Hello World from main()\n"); return 0; }