Calling Global Constructors: Difference between revisions

[unchecked revision][unchecked revision]
Line 7:
The System V ABI (as used by <tt>i686-elf-gcc</tt>, <tt>x86_64-elf-gcc</tt>, and other ELF platforms) specifies use of five different object files that together handle program initialization. These are traditionally called <tt>crt0.o</tt>, <tt>crti.o</tt>, <tt>crtbegin.o</tt>, <tt>crtend.o</tt>, and <tt>crtn.o</tt>. Together these object files implement two special functions: <tt>_init</tt> which runs the global constructors and other initialization tasks, and <tt>_fini</tt> that runs the global destructors and other termination tasks.
 
This scheme gives the compiler great control in program initialization and makes things easy for you, but you have to cooperate with the compiler, otherwise bad things will happen. Your cross-compiler will provide you with <tt>crtbegin.o</tt> and <tt>crtend.o</tt>. These files contain the internals that the compiler wish to hide from you, but wants you to use. To get access to this information, you will need to provide your own implementation of <tt>crti.o</tt> and <tt>crtn.o</tt>. Fortunately, this is easy and is described in detail in this tutorial. The fifth file <tt>crt0.o</tt> contains the program entry point (normally <tt>_start</tt>) and calls the special <tt>_init</tt> function that runs the "program initialization tasks" that <tt>crti.o</tt>, <tt>crtbegin.o</tt>, <tt>crtend.o</tt>, and <tt>crtn.o</tt> together form, and your exit function will normally call the <tt>_fini</tt> function made by these objects. However, <tt>crt0</tt>.o is out of scope of this article. (Note that the object file that contains <tt>_start</tt> acts as <tt>crt0.o</tt> in a kernel.)
 
To understand this apparent complexity, consider a program consisting of <tt>foo.o</tt> and <tt>bar.o</tt> that is being linked:
Anonymous user