__attribute__中constructor和destructor[总结]

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;
}

程序执行结果如下:

3、参考网址

  关于__attribute__的更多更加详细的介绍可以参考:

http://blog.csdn.net/polisan/article/details/5031142

http://blog.csdn.net/ithomer/article/details/6566739

posted @ 2013-12-07 00:50  Rabbit_Dale  阅读(5363)  评论(2编辑  收藏  举报