编译 / __attribute__(constructor)和__attribute__(destructor)
一、前言
最近看代碼,看到一個函數前面用 __attribute__((constructor)) 修飾,搜了整個程序,沒發現哪個地方調用這個函數。如下:
__attribute__((constructor)) void load_file() {printf("Constructor is called.\n");g_count = (int *)malloc(sizeof(int)); }二、__attribute__ 介紹
__attribute__ 可以設置函數屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。
__attribute__ 前后都有兩個下劃線,并且后面會緊跟一對原括弧,括弧里面是相應的__attribute__參數。
__attribute__語法格式為:attribute ( ( attribute-list ) )
如果函數被設定為 constructor 屬性,則該函數會在 main() 函數執行之前被自動的執行;
若函數被設定為 destructor 屬性,則該函數會在 main() 函數執行之后或者 exit() 被調用后被自動的執行。
三、驗證demo程序
例如下面的程序:
#include <stdio.h> #include <stdlib.h> static int * g_count = NULL; __attribute__((constructor)) void load_file() {printf("Constructor is called.\n"); } __attribute__((destructor)) void unload_file() {printf("destructor is called.\n"); }int main() {printf ("this is main function\n");return 0; }執行結果如下:
Constructor is called.
this is main function
destructor is called.
轉載:__attribute__(constructor)和__attribute__(destructor)_sun172270102的博客-CSDN博客___attribute__(constructor)
(SAW:Game Over!)
總結
以上是生活随笔為你收集整理的编译 / __attribute__(constructor)和__attribute__(destructor)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: git / 通过 ssh 与仓库通信
- 下一篇: valgrind 详解