0
点赞
收藏
分享

微信扫一扫

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


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



1. #include <stdio.h> 
2.   
3. __attribute((constructor)) void
4. {  
5. "%s/n",__FUNCTION__);  
6. }  
7.   
8. __attribute((destructor)) void
9. {  
10. "%s/n",__FUNCTION__);  
11. }  
12.   
13. int main( int argc, char
14. {  
15. "%s/n",__FUNCTION__);  
16. return
17. }


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




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



     

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

      before_main

      main

      after_main

     

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



    举报

    相关推荐

    0 条评论