__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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM