__attribute__中constructor和destructor
1、前言
最近看到一份代碼,看到一個函數(shù)前面用__attribute__((destructor))修飾,當時感覺有點怪怪的,搜了整個程序,也沒發(fā)現(xiàn)哪個地方調用這個函數(shù)。于是從字面意思猜想,該函數(shù)會在程序結束后自動調用,與C++中的析構函數(shù)類似。第一次接觸GNU下的attribute,總結一下。
2、__attribute__介紹
__attribute__可以設置函數(shù)屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。__attribute__前后都有兩個下劃線,并且后面會緊跟一對原括弧,括弧里面是相應的__attribute__參數(shù)
__attribute__語法格式為:__attribute__ ( ( attribute-list ) )
若函數(shù)被設定為constructor屬性,則該函數(shù)會在main()函數(shù)執(zhí)行之前被自動的執(zhí)行。類似的,若函數(shù)被設定為destructor屬性,則該函數(shù)會在main()函數(shù)執(zhí)行之后或者exit()被調用后被自動的執(zhí)行。例如下面的程序:
#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;
}程序執(zhí)行結果如下:

3、參考****
關于__attribute__的更多更加詳細的介紹可以參考:
http://blog.csdn.net/polisan/article/details/5031142
http://blog.csdn.net/ithomer/article/details/6566739
GCC __attribute__((constructor)|(destructor))
在閱讀TGTD的代碼時發(fā)現(xiàn)了一個非常詭異的問題,聲明了一個空的全局數(shù)組,在使用的時候卻發(fā)現(xiàn)數(shù)組非空,在main()入口時數(shù)組已經(jīng)非空.數(shù)組時在什么地方被賦值了呢?最后發(fā)現(xiàn)__attribute__這個東東在起作用,類似于全局變量類的構造函數(shù)在main()前被調用.
__attribute__((constructor))
__attribute__((destructor))
*博客內容為網(wǎng)友個人發(fā)布,僅代表博主個人觀點,如有侵權請聯(lián)系工作人員刪除。



