在C++工程中main函数之前跑代码的廉价方法(使用全局变量和全局函数)

[cpp] view plain copy
 
  1. // test.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include <windows.h>  
  6. #include <crtdbg.h>  
  7.   
  8. /// 在C++工程中main函数之前跑代码的廉价方法  
  9. /// 利用全局变量可以赋可变初值的事实  
  10. /// mainCRTStartup() => _cinit() => 全局变量(静态, 普通)赋初值  
  11.   
  12. extern "C" int foo(void);  
  13. extern "C" int foo1(void);  
  14.   
  15. /// 执行顺序和全局变量声明顺序相同  
  16. /// 先执行foo1, 再执行foo();  
  17. static int gs_iTest = foo1();  
  18. int g_iTest = foo();  
  19.   
  20. int main(int argc, char* argv[])  
  21. {  
  22.     printf("&main = %p ", &main);  
  23.     getchar();  
  24.     return 0;  
  25. }  
  26.   
  27. extern "C" int foo(void)  
  28. {  
  29.     /// 执行不带CRT函数的代码  
  30.     MessageBox(NULL, "foo before main", "test", MB_OK);  
  31.     return 0;  
  32. }  
  33.   
  34. extern "C" int foo1(void)  
  35. {  
  36.     /// 执行不带CRT函数的代码  
  37.     MessageBox(NULL, "foo1 before main", "test", MB_OK);  
  38.     return 0;  
  39. }  

效果

http://blog.csdn.net/lostspeed/article/details/49748951

原文地址:https://www.cnblogs.com/findumars/p/5187285.html