在gcc中,可以使用attribute關鍵字,聲明constructor和destructor,來指定了函數在main之前或之后運行,代碼如下:
1 #include <stdio.h> 2 3 __attribute((constructor)) void before_main() 4 { 5 printf("%s/n",__FUNCTION__); 6 } 7 8 __attribute((destructor)) void after_main() 9 { 10 printf("%s/n",__FUNCTION__); 11 } 12 13 int main( int argc, char ** argv ) 14 { 15 printf("%s/n",__FUNCTION__); 16 return 0; 17 }
當然也可以指派多個,而且在申明時?
void before() __attribute__((constructor));
void __attribute__((constructor)) before();
__attribute__((constructor)) void before();
這3種都是對的,__attribute__(())寫法比較隨意,當一般推薦放在后面,當然定義函數體的時候 __attribute__(()) 不能放在后面,推薦定義函數的時候一般不要使用,這就是為什么推薦第一種的原因,__attribute__屬性列表的用法還有還多,內存對齊,函數格 式, 等等等等就不一一列舉了。man gcc 查找下 __attribute__可以發現這些,另標準庫和Linux內核里面也有不少。
也可以一次指定多個屬性 如下:
1 void func(void) __attribute__((constructor destructor));
?
在Windows的VC++中可以指定設定數據段來做,以實現同樣功能,如下:
1 #include <stdio.h> 2 3 int main(int argc, char ** argv) 4 { 5 printf("%s\n", "main"); 6 return 0; 7 } 8 9 int before() 10 { 11 printf("%s\n", "before"); 12 return 0; 13 } 14 15 int after() 16 { 17 printf("%s\n", "after"); 18 return 0; 19 } 20 21 typedef int func(); 22 23 #pragma data_seg(".CRT$XIU") 24 static func *before_function_array[] = { before }; 25 26 #pragma data_seg(".CRT$XPU") 27 static func *after_function_array[] = { after }; 28 29 #pragma data_seg()
?
attribute還有個應用, 就是增加函數別名(下面那個就不能是main了,要不就重復定義了):
# include <stdio.h> int main(int argc, char **argv) __attribute__((alias("LinuxMain")));int LinuxMain(int argc, char **argv) {printf("%s\n", __func__);return 0; }int main123(int argc, char **argv) {printf("%s\n", __func__);return 0; }
?