博客專欄

EEPW首頁 > 博客 > __attribute__中constructor和destructor

__attribute__中constructor和destructor

發(fā)布人:電子禪石 時間:2022-03-16 來源:工程師 發(fā)布文章

1、前言

  最近看到一份代碼,看到一個函數(shù)前面用__attribute__((destructor))修飾,當時感覺有點怪怪的,搜了整個程序,也沒發(fā)現(xiàn)哪個地方調(diào)用這個函數(shù)。于是從字面意思猜想,該函數(shù)會在程序結(jié)束后自動調(diào)用,與C++中的析構(gòu)函數(shù)類似。第一次接觸GNU下的attribute,總結(jié)一下。

2、__attribute__介紹

  __attribute__可以設(shè)置函數(shù)屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。__attribute__前后都有兩個下劃線,并且后面會緊跟一對原括弧,括弧里面是相應(yīng)的__attribute__參數(shù)

  __attribute__語法格式為:__attribute__ ( ( attribute-list ) )

  若函數(shù)被設(shè)定為constructor屬性,則該函數(shù)會在main()函數(shù)執(zhí)行之前被自動的執(zhí)行。類似的,若函數(shù)被設(shè)定為destructor屬性,則該函數(shù)會在main()函數(shù)執(zhí)行之后或者exit()被調(diào)用后被自動的執(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í)行結(jié)果如下:



3、參考****

  關(guān)于__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__這個東東在起作用,類似于全局變量類的構(gòu)造函數(shù)在main()前被調(diào)用.

__attribute__((constructor))
__attribute__((destructor))

__attribute__中constructor和destructor - AlanTu - 博客園 (cnblogs.com)


*博客內(nèi)容為網(wǎng)友個人發(fā)布,僅代表博主個人觀點,如有侵權(quán)請聯(lián)系工作人員刪除。



關(guān)鍵詞: gcc

相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉