Tuesday, September 28, 2010

How to call a function before main and after main

1. Using GCC compiler on Linux/Solaris

/*main.c :this program tells how we can call a function before main() call and after main() call*/

#include

void my_ctor (void) __attribute__ ((constructor));
void my_dtor (void) __attribute__ ((destructor));

void
my_ctor (void)
{
printf ("hello before main()\n");
}

void
my_dtor (void)
{
printf ("bye after main()\n");
}

int
main (void)
{
printf ("hello\n");
return 0;
}

$gcc main.c
$./a.out
hello before main()
hello
bye after main()


2. Using CC compiler on Solaris[Using Pragma]

Using pragma
============


#pragma init (foo)

void foo()
{
printf("\nInside foo");
}

#pragma fini (bar)

void bar()
{
printf("\nInside bar");
}

int
main()
{
printf("\nInside main");
return 0;
}

$cc main.c
$./a.out
Inside foo
Inside main
Inside bar

No comments: