Skip to main content

Execute C Function Before Main

In C, you can execute a particular function before main() using the constructor attribute.

The constructor attribute allows you to specify a function to be called automatically before main() is executed. This function is typically used for initialization purposes.

Here's an example of how you can use the constructor attribute to execute a function before main():

#include <stdio.h>

void my_function(void) __attribute__ ((constructor));

void my_function(void)
    printf("This function is called before main()\n");

int main()
    printf("This is the main function\n");
    return 0;
This function is called before main()
This is the main function

In this example, we have defined a function my_function() and used the __attribute__ ((constructor)) syntax to mark it as a constructor function. When the program is executed, my_function() will be called automatically before main().

Note that the order in which constructor functions are executed is not guaranteed. If you have multiple constructor functions, their order of execution is undefined.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment