关于GCC的__attribute__ ((constructor))

  gcc为函数提供了几种类型的属性,其中包含:构造函数(constructors)和析构函数(destructors)。

程序员应当使用类似下面的方式来指定这些属性:

    static void start(void) __attribute__ ((constructor));
    static void stop(void) __attribute__ ((destructor));
带有"构造函数"属性的函数将在main()函数之前被执行,而声明为"析构函数"属性的函数则将在main()退出时执行。
    下面给出一个简单的程序作为例子:
/* test.c */  
  
#include<stdio.h>  
__attribute__((constructor)) void before_main()  
{  
   printf("before main/n");  
}  
  
__attribute__((destructor)) void after_main()  
{  
   printf("after main/n");  
}  
  
int main()  
{  
   printf("in main/n");  
   return 0;  
}  

[root@localhost tmp]# gcc -o test test.c
[root@localhost tmp]# ./test 
before main function
init main function
after main function


为了便于单元测试,做了一个utl_cmd的小模块,它会负责插入命令,解析命令并执行。

利用这些命令,可以方便的在程序运行过程中对模块进行测试。

而这里有个比较麻烦的问题是,必须要调用utl_cmd_insert先把测试命令插入到命令序列中。

否则utl_cmd模块,也不知道都有哪些命令可以支持。

利用构造函数(constructors)这个特性,就不需要再在main函数中先调用插入命令的函数了。


[cpp]  view plain copy
  1. int mplayer_test_init() __attribute__((constructor)) ;  
  2.   
  3. int mplayer_test_init()  
  4. {  
  5.     char *helper =   
  6.         "\tmplayer prepare [WINDOW COUNT]\n"  
  7.         "\tmplayer play [chn] [fname]\n"  
  8.         "\tmplayer stop [chn]\n"  
  9.         "\tmplayer over\n"  
  10.         "\tmplayer step [chn]\n"  
  11.         "\tmplayer back [chn]\n"  
  12.         "\tmplayer fast [chn] [speed 2,4,8,16,32]\n"  
  13.         "\tmplayer slow [chn] [speed 2,4,8,16,32]\n"  
  14.         "\tmplayer pause [chn]\n"  
  15.         "\tmplayer resume [chn]\n"  
  16.         "\tmplayer allplay\n"  
  17.         "\tmplayer allspeed [fast | slow] [speed]\n"  
  18.         "\tmplayer allstop\n"  
  19.         ;  
  20.     utl_cmd_insert("mplayer""mplayer test", helper, mplayer_main);  
  21.     return 0;  
  22. }  

还有个需要注意之处:

如果,测试代码在一个单独的模块,单独的文件中,而这个文件中的任何函数都没被外部调用的话,

可能会导致自动运行不成功。

原因是,链接过程中,将这个文件整个的删除掉了。

为了避免此问题的发生,可以在链接时,加入-Wl,--whole-archive -l(你的库) -Wl,--no-whole-archive 来避免此问题






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值