语言中如何在main函数开始前执行函数
2015-07-28 19:17
656 查看
在gcc中,可以使用attribute关键字,声明constructor和destructor,代码如下:
#include <stdio.h>
__attribute((constructor)) void before_main()
{
printf("%s/n",__FUNCTION__);
}
__attribute((destructor)) void after_main()
{
printf("%s/n",__FUNCTION__);
}
int main( int argc, char ** argv )
{
printf("%s/n",__FUNCTION__);
return 0;
}
vc不支持attribute关键字,在vc中,可以使用如下方法:
#include <stdio.h>
int main( int argc, char ** argv )
{
printf("%s/n",__FUNCTION__);
return 0;
}
int before_main()
{
printf("%s/n",__FUNCTION__);
return 0;
}
int after_main()
{
printf("%s/n",__FUNCTION__);
return 0;
}
typedef int func();
#pragma data_seg(".CRT$XIU")
static func * before[] = { before_main };
#pragma data_seg(".CRT$XPU")
static func * after[] = { after_main };
#pragma data_seg()
编译执行,上述两段代码的结果均为:
before_main
main
after_main
(vc中可能不支持__FUNCTION__来获得函数名,你可以用另外的方式来获取,比如在befor_main()函数中printf("befor_main()\n");来模拟__FUNCTION__的功能!嘿嘿)
可以在main前后调用多个函数,在gcc下使用attribute声明多个constructor、destructor,vc下在before、after数组中添加多个函数指针。
#include <stdio.h>
__attribute((constructor)) void before_main()
{
printf("%s/n",__FUNCTION__);
}
__attribute((destructor)) void after_main()
{
printf("%s/n",__FUNCTION__);
}
int main( int argc, char ** argv )
{
printf("%s/n",__FUNCTION__);
return 0;
}
vc不支持attribute关键字,在vc中,可以使用如下方法:
#include <stdio.h>
int main( int argc, char ** argv )
{
printf("%s/n",__FUNCTION__);
return 0;
}
int before_main()
{
printf("%s/n",__FUNCTION__);
return 0;
}
int after_main()
{
printf("%s/n",__FUNCTION__);
return 0;
}
typedef int func();
#pragma data_seg(".CRT$XIU")
static func * before[] = { before_main };
#pragma data_seg(".CRT$XPU")
static func * after[] = { after_main };
#pragma data_seg()
编译执行,上述两段代码的结果均为:
before_main
main
after_main
(vc中可能不支持__FUNCTION__来获得函数名,你可以用另外的方式来获取,比如在befor_main()函数中printf("befor_main()\n");来模拟__FUNCTION__的功能!嘿嘿)
可以在main前后调用多个函数,在gcc下使用attribute声明多个constructor、destructor,vc下在before、after数组中添加多个函数指针。
相关文章推荐
- HDU 5319 Painter (模拟 脑洞题)
- 2015 Multi-University Training Contest 3
- Acboy needs your help again!
- Failed to install *.apk on device 'emulator-5554': timeout
- 2015 Multi-University Training Contest 3(hdu 5316、5317、5319、5323、5325、5326)线段树+数学+yy+矩阵快速幂
- 2015 Multi-University Training Contest 3
- Aizu 0009 Prime Number
- this,static,main参数作用,方法,对象的生存
- Rails Model验证之强大
- Kafka设计解析(三):Kafka High Availability (下)
- HDU2124——Repair the Wall(贪心水题)
- Kafka设计解析(二):Kafka High Availability (上)
- [Poj3523][Uva1601][Aizu1281] The Morning after Halloween 【A*算法】
- Aizu 0005 GCD and LCM
- 一次AIX系统报错的问题处理思路
- Ubuntu 下 su:authentication failure的解决办法
- LeetCode 11 -- Container With Most Water
- Core Animaiton - 5
- Snail—OC学习之本地数据持久化(归档)
- hdu_1789_Doing Homework again