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

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

[cpp] view plain copy print ?
  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. }  
#include <stdio.h> __attribute((constructor)) void before_main() { printf("%s/n",__FUNCTION__); } __attribute((destructor)) void after_main() { printf("%s/n",__FUNCTION__); } int main( int argc, char ** argv ) { printf("%s/n",__FUNCTION__); return 0; }

 

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

[cpp] view plain copy print ?
  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()  
#include <stdio.h> int main( int argc, char ** argv ) { printf("%s/n",__FUNCTION__); return 0; } int before_main() { printf("%s/n",__FUNCTION__); return 0; } int after_main() { printf("%s/n",__FUNCTION__); return 0; } typedef int func(); #pragma data_seg(".CRT$XIU") static func * before[] = { before_main }; #pragma data_seg(".CRT$XPU") static func * after[] = { after_main }; #pragma data_seg()

 

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

  before_main

  main

  after_main

 

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


你可能感兴趣的:(c,function,gcc,语言,Constructor,destructor)