__attribute__中constructor和destructor

 

1,__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;
}

程序執行結果如下:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章