编译 / __attribute__(constructor)和__attribute__(destructor)
一、前言
最近看代码,看到一个函数前面用 __attribute__((constructor)) 修饰,搜了整个程序,没发现哪个地方调用这个函数。如下:
__attribute__((constructor)) void load_file()
{printf("Constructor is called.\n");g_count = (int *)malloc(sizeof(int));
}
二、__attribute__ 介绍
__attribute__ 可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。
__attribute__ 前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数。
__attribute__语法格式为:attribute ( ( attribute-list ) )
如果函数被设定为 constructor 属性,则该函数会在 main() 函数执行之前被自动的执行;
若函数被设定为 destructor 属性,则该函数会在 main() 函数执行之后或者 exit() 被调用后被自动的执行。
三、验证demo程序
例如下面的程序:
#include
#include
static int * g_count = NULL;
__attribute__((constructor)) void load_file()
{printf("Constructor is called.\n");
}
__attribute__((destructor)) void unload_file()
{printf("destructor is called.\n");
}int main()
{printf ("this is main function\n");return 0;
}
执行结果如下:
Constructor is called.
this is main function
destructor is called.
转载:__attribute__(constructor)和__attribute__(destructor)_sun172270102的博客-CSDN博客___attribute__(constructor)
(SAW:Game Over!)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
