"); //-->
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
GCC __attribute__((constructor)|(destructor))
__attribute__中constructor和destructor - AlanTu - 博客园 (cnblogs.com)*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。
相关推荐
AVR 单片机与GCC 编程V1.1版
Makefile的编写指导
arm-linux-gcc 不认arm宏汇编??
Linux上安装GCC3.4.0编译器过程
m68k-elf-gcc编译的问题....
新手求助:构造ecos环境时遇到的问题。
GCC 中文手册
国嵌应用班-1-1(GCC程序编译)
AVR 单片机GCC 程序设计
arm-elg-gcc 怎么编译不了msr cpsr_cf, r1
AVRGCC/WinAVR编译环境中断函数的使用方法
ICC GCC傻傻分不清?聊一聊编译器那些事儿
基于Atmega16L的简单音乐制作
基于ARM11嵌入式远程监控系统的分析与设计
winavr gcc快速入门
用arm-linux-gcc.4.3.2交叉编译器编译linux-3.0.1内核
在AVR Studio里使用AVR-GCC
交叉编译链arm-linux-gcc-3.3.2在ubuntu10.04下的安装
[求助]arm-linux-gcc找不到标准库函数math.h,什么原因呢?
剖析C语言中a=a+++++a的无聊问题
GCC-维基百科