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

Here we will see how to write a code where two functions are present, and one function will be executed before the main function, and another function will be executed after the main function. These features are used to do some startup task before executing the main, and some cleanup task after executing main.

To do this task we have to put attribute for these two functions. When the attribute is constructor attribute, then it will be executed before main(), and when the attribute is destructor type, then it will be executed after main().

Syntax

void function_name() __attribute__((constructor));
void function_name() __attribute__((destructor));

Example

The following example demonstrates constructor and destructor attributes −

#include <stdio.h>

void before_main() __attribute__((constructor));
void after_main() __attribute__((destructor));

void before_main() {
    printf("This is executed before main.<br>");
}

void after_main() {
    printf("This is executed after main.<br>");
}

int main() {
    printf("Inside main<br>");
    return 0;
}
This is executed before main.
Inside main
This is executed after main.

Key Points

  • Constructor functions execute automatically before main() begins.
  • Destructor functions execute automatically after main() ends.
  • These are GCC-specific attributes and may not be portable across all compilers.
  • Multiple constructor and destructor functions can be defined with priority values.

Conclusion

Constructor and destructor attributes provide a way to execute initialization and cleanup code automatically. They are useful for setting up resources before main execution and cleaning up afterward.

Updated on: 2026-03-15T10:25:52+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements