写个函数在main函数执行前运行

本文讨论3种 使函数在main函数执行前运行的方法:

1.使用attribute关键字,声明constructor和destructor函数(gcc中,注意:vc中不支持attribute)
2.通过段名称“…CRT$XIU”,“.CRT$XCU”把函数放在“C/C++初始化函数表”中
3.利用全局对象的构造函数会在main函数之前执行的特点

具体实现代码如下,该代码在VC++中验证通过:

#include <iostream>

using namespace std;

//0.gcc中使用attribute关键字,声明constructor和destructor函数
/*
//vc中不支持attribute
__attribute((constructor))void before()
{
    printf("before main\n");
}
*/

//
//1.通过段名称“.CRT$XIU”,“.CRT$XCU”把函数表放在“C/C++初始化函数表”中
//通过特殊的段名称“.CRT$XIU”,“.CRT$XCU”,
//链接器会把before1表放在“C初始化函数表”中,类似这样
//[__xi_a, ..., before1(xiu), ..., __xi_z].
//同理,before2表会被链接器放在“C++初始化函数表”中,象这样
//[__xc_a, ..., before2(xcu), ..., __xc_z],

int before_main1()  
{  
	printf("before_main1()\n");  

	return 0;  
}  
int before_main2()  
{  
	printf("before_main2()\n");  

	return 0;  
}  
int after_main()
{
	printf("after_main()\n");
	return 0;
}

typedef int func(); 

#pragma data_seg(".CRT$XIU")  //用#pragma data_seg建立一个新的数据段并定义共享数据
//static func * before1[] = { before_main1 };  
func *before1 = before_main1;

#pragma data_seg(".CRT$XCU")  
//static func * before2[] = { before_main2 };  
func *before2 = before_main2;

#pragma data_seg() 

//
//2.全局对象的构造函数会在main函数之前执行
class my_class{
public:
	my_class()
	{
		cout<<"my class constructor"<<endl;
	}
	~my_class()
	{
		cout<<"my class destructor"<<endl;
	}
};

my_class test;

void main()
{
	_onexit(after_main);
	cout<<"this's main start"<<endl;
}

以下是输出结果:
before_main1()
before_main2()
my class constructor
this’s main start
after_main()

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值