Calling Global Constructors: Difference between revisions

Jump to navigation Jump to search
[unchecked revision][unchecked revision]
Content added Content deleted
Line 11: Line 11:
To understand this apparent complexity, consider a program consisting of <tt>foo.o</tt> and <tt>bar.o</tt> that is being linked:
To understand this apparent complexity, consider a program consisting of <tt>foo.o</tt> and <tt>bar.o</tt> that is being linked:


<source lang="bash">i585-elf-gcc foo.o bar.o -o program</source>
<source lang="bash">i586-elf-gcc foo.o bar.o -o program</source>


The compiler will rewrite the command line and pass it to the linker as:
The compiler will rewrite the command line and pass it to the linker as:


<source lang="bash">i585-elf-ld crt0.o crti.o crtbegin.o foo.o bar.o crtend.o crtn.o</source>
<source lang="bash">i586-elf-ld crt0.o crti.o crtbegin.o foo.o bar.o crtend.o crtn.o</source>


The idea is that the these files together form the <tt>_init</tt> and <tt>_fini</tt> functions during the linking. This is done by storing the <tt>_init</tt> function in the <tt>.init</tt> section, and the <tt>_fini</tt> function in the <tt>.fini section</tt>. Each file then contributes a bit to these sections and the linker makes glues together the fragments in the code specified on the command line. <tt>crti.o</tt> provides the function header, <tt>crtbegin.o</tt> and <tt>crtend.o</tt> provide the body, and <tt>crtn.o</tt> provide the footer (return statement). It is important to understand that the link order matters and strange things may happen if the objects is not exactly linked in this order.
The idea is that the these files together form the <tt>_init</tt> and <tt>_fini</tt> functions during the linking. This is done by storing the <tt>_init</tt> function in the <tt>.init</tt> section, and the <tt>_fini</tt> function in the <tt>.fini section</tt>. Each file then contributes a bit to these sections and the linker makes glues together the fragments in the code specified on the command line. <tt>crti.o</tt> provides the function header, <tt>crtbegin.o</tt> and <tt>crtend.o</tt> provide the body, and <tt>crtn.o</tt> provide the footer (return statement). It is important to understand that the link order matters and strange things may happen if the objects is not exactly linked in this order.