閱讀878 返回首頁    go 阿裏雲 go 技術社區[雲棲]


C語言中如何在main函數開始前執行函數

在gcc中,可以使用attribute關鍵字,聲明constructordestructor,代碼如下:

  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. }  

 

  vc不支持attribute關鍵字,在vc中,可以使用如下方法:

  1. #include <stdio.h>  
  2.   
  3. int  
  4. main( int argc, char ** argv )  
  5. {  
  6.         printf("%s/n",__FUNCTION__);  
  7.   
  8.         return 0;  
  9. }  
  10.   
  11.   
  12. int before_main()  
  13. {  
  14.         printf("%s/n",__FUNCTION__);  
  15.   
  16.         return 0;  
  17. }  
  18.   
  19. int after_main()  
  20. {  
  21.         printf("%s/n",__FUNCTION__);  
  22.   
  23.         return 0;  
  24. }  
  25.   
  26. typedef int func();  
  27.   
  28. #pragma data_seg(".CRT$XIU")  
  29. static func * before[] = { before_main };  
  30.   
  31. #pragma data_seg(".CRT$XPU")  
  32. static func * after[] = { after_main };  
  33.   
  34. #pragma data_seg()  

 

  編譯執行,上述兩段代碼的結果均為:

  before_main

  main

  after_main

 

  可以在main前後調用多個函數,在gcc下使用attribute聲明多個constructordestructor,vc下在before、after數組中添加多個函數指針。

最後更新:2017-04-03 19:13:18

  上一篇:go 哈佛/MIT學生創造GPU數據庫,性能提升70倍
  下一篇:go J2EE中RequestDispatcher.forward()和response.sendRedirect()的區別詳談