Open In App

Functions that are executed before and after main() in C

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

With GCC family of C compilers, we can mark some functions to execute before and after main(). So some startup code can be executed before main() starts, and some cleanup code can be executed after main() ends. For example, in the following program, myStartupFun() is called before main() and myCleanupFun() is called after main().




#include<stdio.h>
  
/* Apply the constructor attribute to myStartupFun() so that it
    is executed before main() */
void myStartupFun (void) __attribute__ ((constructor));
  
  
/* Apply the destructor attribute to myCleanupFun() so that it
   is executed after main() */
void myCleanupFun (void) __attribute__ ((destructor));
  
  
/* implementation of myStartupFun */
void myStartupFun (void)
{
    printf ("startup code before main()\n");
}
  
/* implementation of myCleanupFun */
void myCleanupFun (void)
{
    printf ("cleanup code after main()\n");
}
  
int main (void)
{
    printf ("hello\n");
    return 0;
}


Output:

startup code before main()
hello
cleanup code after main()

Like the above feature, GCC has added many other interesting features to standard C language. See this for more details.

Related Article :
Executing main() in C – behind the scene


Last Updated : 28 May, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads