设置在main 之前运行的函数

本文深入探讨了C++中全局对象构造函数的执行时机,特别关注其在main函数之前运行的特点,并展示了如何利用__attribute__((constructor))关键字指定函数在main函数之前或之后运行。此外,文章还介绍了__attribute__关键字的多种用法及其实现内存对齐、函数样式等特性,并提供了与之相关的属性列表用法示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.youkuaiyun.com/dengxu11/article/details/6708269       

        我们知道 C++的对象全局对象的构造函数会在main之前运行,例如windows MFC里面,在WinMain 函数前声明了一个theApp对象,其构造函数就在WinMain之前运行,其实在C语言中很早就有了,在gcc中可以使用__attribute__关键字指定如下(注意,这个和诸如on exit之类可不一样,这个是编译器编译的时候就决定了的)

  1. #include <stdio.h>  
  2. void before() __attribute__((constructor));  
  3. void after() __attribute__((destructor));  
  4.   
  5. void before()  
  6. {  
  7.     printf("this is function %s/n", __func__);  
  8.     return;  
  9. }  
  10.   
  11. void after()  
  12. {  
  13.     printf("this is function %s/n", __func__);  
  14.     return;  
  15. }  
  16.   
  17. int main(int argc, char **argv)  
  18. {  
  19.     printf("this is function %s/n", __func__);  
  20.     return 0;  
  21. }  
指定了函数在main之前或之后运行。
当然也可以指派多个,而且在申明时 
void before() __attribute__((constructor));
void __attribute__((constructor)) before();
__attribute__((constructor)) void before();

这3种都是对的,__attribute__(())写法比较随意,当一般推荐放在后面,当然定义函数体的时候 __attribute__(()) 不能放在后面,推荐定义函数的时候一般不要使用,这就是为什么推荐第一种的原因,__attribute__属性列表的用法还有还多,内存对齐,函数格式, 等等等等就不一一列举了。man gcc 查找下 __attribute__可以发现这些,另标准库和Linux内核里面也有不少。

也可以一次指定多个属性 如下:

  1. void func(void) __attribute__((constructor destructor));  

attribute 是gcc、 g++的关键字,VC是不能用这个的,

如果您是在Windows下你可以指定设定数据段来做,以实现同样功能,如下:

  1. #include <stdio.h>  
  2.    
  3. int main(int argc, char ** argv)  
  4. {  
  5.     printf("%s\n""main");  
  6.     return 0;  
  7. }  
  8.    
  9. int before()  
  10. {  
  11.     printf("%s\n""before");  
  12.     return 0;  
  13. }  
  14.    
  15. int after()  
  16. {  
  17.     printf("%s\n""after");  
  18.     return 0;  
  19. }  
  20.   
  21. typedef int func();  
  22.   
  23. #pragma data_seg(".CRT$XIU")  
  24. static func *before_function_array[] = { before };  
  25.   
  26. #pragma data_seg(".CRT$XPU")  
  27. static func *after_function_array[] = { after };  
  28. #pragma data_seg() 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值