Constructor and Destructor for C Program
In Category C/C++
constructor and destructor attributes can be used to define a constructor function and a destructor function for a C program. In the following example pg_init function is defined as constructor and this function gets invoked before main() function. The pg_deinit function is defined as destructor and it gets invoked before process exits.
Download: condes.c
#include <stdio.h>
static void pg_init () __attribute__ ((constructor));
static void pg_deinit () __attribute__ ((destructor));
static void
pg_init()
{
printf("program init...........\n");
}
static void
pg_deinit()
{
printf("program deinit...........\n");
}
int main()
{
printf("This is main\n");
}
The following is the output.
[neo@techpulp ~]# gcc condes.c -o condes [neo@techpulp ~]# [neo@techpulp ~]# ./condes program init........... This is main program deinit........... [neo@techpulp ~]#