独立于main运行的程序
#include <iostream> using namespace std; #define INITIALIZER(f) \ static void f(void) __attribute__((constructor)); \ static void f(void) #define DEINITIALIZER(f) \ static void f(void) __attribute__((destructor)); \ static void f(void) static void IniFunc(){ int a = 1+1; printf("func()---1+1= %d\n",a); printf("func()---can not use std::cout \n"); //cout<<"func()"<<endl; } static void deFunc(){ cout<<"~func()"<<endl; int a = 1+2; printf("1+2= %d\n",a); std::cout<<"std::cout"<<std::endl; } INITIALIZER(ff){ IniFunc(); }; DEINITIALIZER(dd){ deFunc(); std::cout<<"can use cout"<<std::endl; }; /* static void f1(void) __attribute__((constructor)); void f1(void){ printf("before main1111\n"); } */ /* void static __attribute__((constructor)) before_main() { printf("before main\n"); } void static __attribute__((destructor)) after_main() { printf("after main\n"); } */ int main(){ cout<< "in main"<<endl; return 0; }
ygy@ygy-VirtualBox:~/work/tmp$ g++ d.cpp ygy@ygy-VirtualBox:~/work/tmp$ ./a.out func()---1+1= 2 func()---can not use std::cout in main ~func() 1+2= 3 std::cout can use cout