本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
网上有说可以用
__attribute__ ((constructor)) 来让函数在main函数之前执行,
__attribute__ ((destructor)) 来让函数在main函数之后执行。
比如说像下面这样声明函数
void before(void) __attribute__ ((constructor));
void after(void) __attribute__ ((destructor)
不过这不是C/C++标准,它用GCC可能正常编译通过,但用其它的编译器不一定可以编译通过
在标准C/C++中
可以用global variable 或static variable来让代码在main函数之前执行
可以用atexit来让函数在main函数之后执行
#include <iostream>
using namespace std;
int before_main(){
cout << "before main" << endl;
return 1;
}
static int a = before_main();
void after_main(){
cout << "after main" << endl;
}
int main(int argc, char *argv[])
{
cout << "main" << endl;
atexit(after_main);
system("pause");
}