Question

Is it possible to call an extra function when main() exits in C?

Thanks!

Was it helpful?

Solution

You can register functions to run after main exits using the atexit function.

MSDN has a nice succinct example of how this is done. Basically, the functions registered with atexit are executed in reverse order of when they were registered.

OTHER TIPS

Try the atexit() function:

void myfunc() {
    /* Called when the program ends */
}

int main( int arc, char *argv[] ) {
    atexit( myfunc );
    ...
    return 0;
}

Great question and answers. Just a side note. Abuse of a similar feature in Delphi libraries led to applications which are annoyingly slow on close.

While atexit() is the standard for registering a function to run at process termination, GCC provides a destructor function attribute* that causes a function to be called automatically when main() has completed or exit() has been called.

void __attribute__ ((destructor)) my_fini(void);

* GCC specific

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top