怎样使代码在main函数前执行,怎样使代码在main函数之后执行

本文为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");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值