在閱讀TGTD的代碼時發現了一個非常詭異的問題,聲明了一個空的全局數組,在使用的時候卻發現數組非空,在main()入口時數組已經非空.數組時在什麼地方被指派了呢?最後發現__attribute__這個東東在起作用,類似于全局變量類的構造函數在main()前被調用.
__attribute__((constructor))
__attribute__((destructor))
/* test.c */
#include<stdio.h>
__attribute__((constructor)) void before_main()
{
printf("before main/n");
}
__attribute__((destructor)) void after_main()
{
printf("after main/n");
}
int main()
{
printf("in main/n");
return 0;
}
$ gcc test.c -o test
$ ./test
before main
in main
after main
根據上面的代碼以及輸出結果,我們可以猜到__attribute__((constructor))表示這段代碼将在main函數前調用,就像在C++裡面的全局變量類的構造一樣.
說到C++裡面的全局類對象的構造,我們不禁要問全局類對象的構造跟__attribute__((constructor))以及destructor誰在前誰在後呢?
#include<iostream>
using namespace std;
__attribute__((constructor)) void before_main()
{
cout<<"Before Main"<<endl;
}
__attribute__((destructor)) void after_main()
{
cout<<"After Main"<<endl;
}
class AAA{
public:
AAA(){
cout<<"AAA construct"<<endl;
}
~AAA(){
cout<<"AAA destructor" <<endl;
}
};
AAA A;
int main()
{
cout<<"in main"<<endl;
return 0;
}
$ make test2
$ ./test2
AAA construct
Before Main
in main
AAA destructor
After Main
可以看到全局類的構造過程發生在before_main()函數前面,而析構也發生在after_main()前面.