您的位置:首页 > 其它

GCC设置函数属性为constructor和destructor

2016-03-26 18:18 447 查看
  在阅读FIO源码过程中,看到引擎的注册函数fio_libaio_register与反注册函数fio_libaio_unregister都没有其他函数调用,而fio又没有以动态库的形式将这两个函数供别的地方使用。。郁闷。。再次看时发现两个函数的前面分别有宏fio_init和fio_exit,其定义为别为:

#define fio_init __attribute__((constructor))
#define fio_exit __attribute__((destructor))
     这不正是C++中的构造函数与析构函数么。。。

     回头看看GCC的属性设置吧。。__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__语法格式为:__attribute__
( ( attribute-list ) )


  若函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行。若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。示例如下:

#include <stdio.h>
#include <stdlib.h>
void __attribute__((constructor)) con_func()
{
printf("befor main: constructor is called..\n");
}
void __attribute__((destructor)) des_func()
{
printf("after main: destructor is called..\n");
}
int main()
{
printf("main func..\n");
return 0;
}
输出:


befor main: constructor is called..
main func..
after main: destructor is called..



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息