编译 / __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 <stdio.h> #include <stdlib.h> 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!)
总结
以上是生活随笔为你收集整理的编译 / __attribute__(constructor)和__attribute__(destructor)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: git / 通过 ssh 与仓库通信
- 下一篇: valgrind 详解