C++中如何在main()函数之前执行操作?

多玩YY语音的面试题:C++中如何在main()函数之前执行操作?

           第一反应main()函数是所有函数执行的开始。但是问题是main()函数执行之前如何执行呢?

           联想到MFC里面的 C**App类的theApp对象,其执行顺序就在main函数之前。道理相通,顺理推下,能够想到:如果在main函数之前声明一个类的全局的对象。那么其执行顺序,根据全局对象的生存期和作用域,肯定先于main函数。

示例如下:

  1. <span style="font-size:14px;">class simpleClass  
  2. {  
  3. public:  
  4.        simpleClass( )  
  5.        {  
  6.               cout << "simpleClass constructor.." << endl;  //step2  
  7.        }  
  8. };  
  9.   
  10.    
  11. simpleClass g_objectSimple;         //step1全局对象  
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  //step3  
  14. {  
  15.        return 0;  
  16. }  
  17.   
  18.   
  19. 可单步调试查看执行顺序为step1、step2、step3。</span>  

 

考虑到全局对象,同理会进一步思考静态对象的作用域。将上述示例进一步扩展如下:

  1. <span style="font-size:14px;">class simpleClass  
  2. {  
  3. public:  
  4.        simpleClass( )  
  5.        {  
  6.               cout << "simpleClass constructor.." << endl;       //step2   
  7.        }  
  8. };  
  9.   
  10. class simpleClassTwo  
  11. {  
  12. public:  
  13.        static simpleClass m_sSimpleClass;  
  14. };  
  15.   
  16. simpleClass simpleClassTwo::m_sSimpleClass = simpleClass(); //step1 静态对象  
  17.   
  18. int _tmain(int argc, _TCHAR* argv[])                        //step3  
  19.   
  20. {  
  21.         return 0;  
  22. }  
  23.   
  24.   
  25. 可单步调试查看执行顺序为step1、step2、step3。</span>  

        至此,我们可以总结出:定义在main( )函数之前的全局对象、静态对象的构造函数在main( )函数之前执行

      再进一步思考,既然可以在main( )函数之前执行全局、静态对象的构造函数。那么有没有函数在main( )函数之后执行呢?

有的,onexit函数。原型如下:

_onexit_t _onexit(

   _onexit_t function

);

_onexit_t_m _onexit_m(

   _onexit_t_m function

);

解释:The _onexit function is passed the address of a function (function) to be called when the program terminates normally. Successive calls to _onexit create a register of functions that are executed in LIFO (last-in-first-out) order. The functions passed to _onexit cannot take parameters.

 

核心点:

1)              执行期——程序执行终止的时候;

2)              传递参数——函数的地址,即函数指针;

3)              执行顺序——后进先出。

 

_onexit is a Microsoft extension. For ANSI portability, use atexit. The _onexit_m version of the function is for mixed mode use.

onexit是微软的扩展版本,标准C++里面应用的是atexit。

【MSDN】示例:

  1. <span style="font-size:14px;">#include <stdlib.h>  
  2. #include <stdio.h>  
  3. /* Prototypes */  
  4. int fn1(void), fn2(void), fn3(void), fn4 (void);  
  5.   
  6. int main( void )  
  7. {  
  8.       _onexit( fn1 );  
  9.       _onexit( fn2 );  
  10.       _onexit( fn3 );  
  11.       _onexit( fn4 );  
  12.       printf( "This is executed first.\n" );  
  13. }  
  14.   
  15.    
  16. int fn1()  
  17. {  
  18.       printf( "next.\n" );  
  19.       return 0;  
  20. }  
  21.   
  22.    
  23. int fn2()  
  24. {  
  25.       printf( "executed " );  
  26.       return 0;  
  27. }  
  28.   
  29.    
  30. int fn3()  
  31. {  
  32.       printf( "is " );  
  33.       return 0;  
  34. }  
  35.   
  36.    
  37. int fn4()  
  38. {  
  39.       printf( "This " );  
  40.       return 0;  
  41. }  
  42.   
  43. </span>  

执行结果如下:

       显然,读程序可以看出main( )函数执行完毕后又执行了onexit( )函数。

      还有没有其他特殊的情况呢?持续探讨、更新中……


2013-4-23更新

补充:控制台界面应用程序是如何启动的?

       以Windows平台为例,用MicrosoftVisual Studio 来创建一个应用程序项目时,集成开发环境会设置各种连接开关,使链接器将子系统的正确类型嵌入最终生成的可执行文件(executable)中。对于控制台界面应用程序,这个链接器的开关是/SUBSYSTEM:CONSOLE。

       用户启动应用程序时,操作系统的加载程序(loader)会检查可执行文件映像的文件头,并获取这个子系统值。如果如下图所示,子系统值为/SUBSYSTEM:CONSOLE,加载程序会自动确保命令符启动程序的时候有一个可用的文本控制台窗口。另外,如有必要,如从资源管理器启动CUI程序的时候,会创建一个新窗口。


       在连接可执行文件时,链接器将选择正确的C/C++运行库启动函数。如果指定了/SUBSYSTEM:CONSOLE,会执行如下步骤:

      

      

       所有C/C++运行库启动函数所做的事情基本都是一样的,区别1在于它们处理字符串的类型(ANSI字符串或者是Unicode字符串),区别2在于它们调用的是哪个入口点函数。

       Visual C++自带C++运行库的源代码启动函数的用途简单概括如下:

1)  获取新进程完整命令行的一个指针;

2)  获取指向新进程的环境变量的一个指针;

3)  初始化C/C++运行库的全局变量。

4)  初始化C运行库内存分配函数(malloc和calloc)和其他底层的I/O例程使用的堆。

5)  调用所有全局和静态C++类对象的构造函数

第5条也就解释了为什么在main()函数前运行全局、静态变量的构造函数了。

 

入口点函数返回后,启动函数将调用C运行库函数exit,向其传递返回值(nMainRetVal)。exit函数执行以下任务

1)  调用_onexit函数所有调用所注册的任何一个函数;

2)  调用所有全局和静态C++类对象的析构函数;

3)  在DEBUG生成中,如果设置了_CRTDBG_LEAK_CHECK_DF标志,就通过调用_CrtDumpMemoryLeaks函数生成内存泄露报告。

4)  调用操作系统的ExitProcess函数,向其传入nMainRetVal。这会导致操作系统杀死我们的进程,并设置它的退出代码。

exit( )函数的执行的先后顺序为:1)、2)、3)、4)。

 

       如下上述程序的合体,验证了exit函数的执行顺序。

       先全局对象构造函数,然后执行main函数打印语句,再执行_onexit注册函数;最后执行全局对象析构函数。

  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.    
  4. class simpleClass  
  5. {  
  6. public:  
  7.        simpleClass()  
  8.        {  
  9.               cout<< "simpleClass constructor.." << endl;  
  10.        }  
  11.        ~simpleClass()  
  12.        {  
  13.               cout<< "~SimpleClass Destructor.." << endl;  
  14.        }  
  15. };  
  16.    
  17. simpleClass g_objectSimple;      //1全局对象  
  18.    
  19. /* Prototypes */  
  20. int fn1(void), fn2(void), fn3(void), fn4(void);  
  21.    
  22. int main( void )  
  23. {  
  24.        _onexit(fn1 );  
  25.        _onexit(fn2 );  
  26.        _onexit(fn3 );  
  27.        _onexit(fn4 );  
  28.        printf("This is executed first.\n" );  
  29. }  
  30.    
  31. int fn1()  
  32. {  
  33.        printf("next.\n" );  
  34.        return0;  
  35. }  
  36.    
  37. int fn2()  
  38. {  
  39.        printf("executed " );  
  40.        return0;  
  41. }  
  42.    
  43. int fn3()  
  44. {  
  45.        printf("is " );  
  46.        return0;  
  47. }  
  48.    
  49. int fn4()  
  50. {  
  51.        printf("This " );  
  52.        return0;  
  53. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章