__attribute__((constructor))

2020-08-09 09:54:07

__attribute__((constructor))

The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () completes or exit () is called. Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.

建構函式屬性使函數在執行進入main()之前自動被呼叫。同樣,解構函式屬性使函數在main()完成或呼叫exit()之後自動被呼叫。具有這些屬性的函數對於初始化在程式執行期間隱式使用的數據很有用。

就是指在函數上方加上__attribute__((constructor))可以讓這個函數在main函數執行前執行

#include<stdio.h>


__attribute__((constructor))
void print(){
    printf("This is print func!\n");
    return ;
}

int main(){
    printf("This is main func!\n");
    return 0;
}

輸出
在这里插入图片描述
可以看到print函數在main函數之前執行了
__attribute__((constructor))可以提前初始化一些在main函數中用到的東西
如果你瞭解AVL樹,可以看一下其程式碼中NIL節點的初始化例子
https://blog.csdn.net/moX980/article/details/107561605