| Understanding The Linux Kernel Initcall Mechanism: Creating Dynamic Function-Pointer Call Tables | |||
|---|---|---|---|
| <<< Previous | Next >>> | Blog | |
Specifying an attribute gives the compiler information about how an object is intended to be used, thereby allowing it to not only better optimize your code but to also perform additional checks for you. In general (using gcc) attributes can be specified for functions, variables, and types. Full information can be found by visiting the GCC onlinedocs website and looking for the relevant subsections on attributes.
Unless you've stumbled across this before, you probably thought that the first line of your main() is the first line of code that gets executed when your executible is run. This isn't true. There are a number of functions that run before your main() gets called. Then after your main() terminates, a number of additional clean-up routines are also called. Your main() is just one of several functions for the loader to run.
gcc allows you to specify functions it should call during the phase before main() is called as well as functions to call during the phase after main() is done. The following code demonstrates this and serves as an example of how to specify attributes on functions.
/*
* Copyright (C) 2006 Trevor Woerner
*/
#include <stdio.h>
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\nbye\n");
return 0;
}
|
Running yields:
[trevor]$ ./ctor_dtor
hello before main()
hello
bye
bye after main()
|
| <<< Previous | Home | Next >>> |
| Compiler | Section and Object Layout |