Friday, October 4, 2013

How to call function before main() function in C

Calling a user defined function before main() function: This is possible using function attributes. The standard C supports attributes syntax which is compiler dependent. C also supports type attributes, variable attributes. For more details about attributes click here.

     Using function attributes, we can call the function before the main function by specifying the parameter as constructor. This will be called at startup and mostly when shared libraries are called. We can also use destructor for calling the method after main() function, which indicates the exit of the application/program.

Below is the sample code:

void beforeMain() __attribute__((constructor));
void afterMain() __attribute__((destructor));

void beforeMain()
        printf("before main \n");

void afterMain()
        printf("after main \n");

int main()
        printf("In main function \n");
        printf("leaving main function \n");

Output: below is the result of the above program.

$ ./a.out
before main
In main function
leaving main function
after main

Explanation: This is because of function attribute constructor will be called at the time of start, before main() function and function attribute destructor will be called at the time of exit, after the main() function.

No comments:

Popular Posts