zl程序教程

您现在的位置是:首页 >  其它

当前栏目

__attribute__中constructor和destructor[总结]

总结 __ attribute constructor
2023-09-14 08:59:45 时间

1、前言

最近看到一份代码,看到一个函数前面用__attribute__((destructor))修饰,当时感觉有点怪怪的,搜了整个程序,也没发现哪个地方调用这个函数。于是从字面意思猜想,该函数会在程序结束后自动调用,与C++中的析构函数类似。第一次接触GNU下的attribute,总结一下。

2、__attribute__介绍

__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数

__attribute__语法格式为:__attribute__ ( ( attribute-list ) )

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

复制代码
#include stdio.h 

#include stdlib.h 

static int * g_count = NULL;

__attribute__((constructor)) void load_file()

 printf("Constructor is called.\n");

 g_count = (int *)malloc(sizeof(int));

 if (g_count == NULL)

 fprintf(stderr, "Failed to malloc memory.\n");

__attribute__((destructor)) void unload_file()

 printf("destructor is called.\n");

 if (g_count)

 free(g_count);

int main()

 return 0;

}
复制代码

程序执行结果如下: