Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer


Registers a routine to be called at exit time.

_onexit_t _onexit(
   _onexit_t func 


Pointer to function to be called at exit.

Return Value

_onexit returns a pointer to the function if successful, or NULL if there is no space to store the function pointer.


The _onexit function is passed the address of a function (func) 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.

In the case when _onexit is called from within a DLL, routines registered with _onexit will run upon a DLL's unloading after DllMain is called with DLL_PROCESS_DETACH.

_onexit is a Microsoft extension. For ANSI portability use atexit.


Routine Required header Compatibility
_onexit <stdlib.h> Win 98, Win Me, Win NT, Win 2000, Win XP

For additional compatibility information, see Compatibility in the Introduction.


All versions of the C run-time libraries.


// crt_onexit.c

#include <stdlib.h>
#include <stdio.h>

/* Prototypes */
int fn1(void), fn2(void), fn3(void), fn4 (void);

int main( void )
   _onexit( fn1 );
   _onexit( fn2 );
   _onexit( fn3 );
   _onexit( fn4 );
   printf( "This is executed first.\n" );

int fn1()
   printf( "next.\n" );
   return 0;

int fn2()
   printf( "executed " );
   return 0;

int fn3()
   printf( "is " );
   return 0;

int fn4()
   printf( "This " );
   return 0;


This is executed first.
This is executed next.

See Also

Process and Environment Control Routines | atexit | exit | Run-Time Routines and .NET Framework Equivalents

© 2016 Microsoft