Tuesday 3 November 2015

How to call a function before the execution of main function or after the execution of main function in a C program ?

A program which shows two functions which are called before and after main respectively. (It works in GCC compiler).
Code:

#include<stdio.h>

void myStartupFun(void) __attribute__ ((constructor ));
void myCleanupFun(void) __attribute__ ((destructor ));

void myStartupFun(void) {

printf("This is called before main.\n");

}

void myCleanupFun(void) {

printf("This is called after main.\n");

}

void main(){

printf("This is main function.");
}

Output: 
This is called before main.
This is main function.
This is called after main.

Explanation: 
This works in a similar manner as a Constructor or Destructor in OOPS.
__atttribute__ runs when a shared library is loaded during loading steps in C program execution. It uses two brackets to distinguish them from function calls.
__atttribute__ is not a macro or function , it is a GCC-specific syntax.



There is yet another way of doing above task, which is by using #pragma directive. 

No comments:

Post a Comment