C语言中如何在main函数开始前执行函数

 在gcc中,可以使用attribute关键字,声明constructor和destructor,代码如下:

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

  编译执行,上述两段代码的结果均为:

  before_main

  main

  after_main

 (vc中可能不支持__FUNCTION__来获得函数名,你可以用另外的方式来获取,比如在befor_main()函数中printf("befor_main()\n");来模拟__FUNCTION__的功能!嘿嘿)

  可以在main前后调用多个函数,在gcc下使用attribute声明多个constructor、destructor,vc下在before、after数组中添加多个函数指针。

posted on 2011-08-19 13:13  原来...  阅读(5016)  评论(0编辑  收藏  举报

导航