可以使用atexit()函数注册一个函数
- #include <stdlib.h>
- //功能:Processes the specified function at exit.
- //格式:int atexit( void ( __cdecl *func )( void ) );
- //描述:The atexit function is passed the address of a function (func) to be
- // called when the program terminates normally. Successive calls to atexit
- //create a register of functions that are executed in LIFO (last-in-first-out)
- //order. The functions passed to atexit cannot take parameters. atexit and
- //_onexit use the heap to hold the register of functions. Thus, the number of
- // functions that can be registered is limited only by heap memory.
- int atexit (void (*function)(void));
- #include <stdio.h>
- void fun1(void);
- void fun2(void);
- void fun3(void);
- void fun4(void);
- void main()
- {
- atexit(fun1);
- atexit(fun2);
- atexit(fun3);
- atexit(fun4);
- printf("this is executed first.\n");
- }
- void fun1()
- {
- printf("next.\n");
- }
- void fun2()
- {
- printf("executed ");
- }
- void fun3()
- {
- printf("is ");
- }
- void fun4()
- {
- printf("this ");
- }
结果:
This is executed first.
This is executed next.
注意,atexit()以栈的方式注册函数,后注册的函数会先执行
全局类的析构函数好象也在main后执行
non-local static object的构造函数在main之前执行,析构函数在main之后执行。
关于这些函数是如何执行的,以及atexit注册的函数是如何被执行的,可以参见crt的源文件。
在vc.net中,这个文件应该是在...\Microsoft Visual Studio .NET 2003\Vc7\crt\src\crt0.c
通过step into,你也可以跟踪整个程序被crt控制执行的过程。