Calling Global Constructors: Difference between revisions

Undo revision 17566 by Exetwezz (talk)
[unchecked revision][unchecked revision]
(Grammar fix)
(Undo revision 17566 by Exetwezz (talk))
Line 39:
== Using crti.o, crtbegin.o, crtend.o, and crtn.o in a Kernel ==
 
In a kernel, you are not using a user-space C library. You may be using a special kernel "C library", or none at all. The compiler always supplies <tt>crtbegin.o</tt> and <tt>crtend.o</tt>, but normally the C library supplies <tt>crti.o</tt> and <tt>crtn.o</tt>, but not in this case. The kernel should supply its own <tt>crti.o</tt> and <tt>crtn.o</tt> implementation (even if it would be otherwise identical to the user-space libc version). A kernel is linked with <tt>-nostdlib</tt> (which is the same as passing <tt>-nodefaultlibs</tt> and <tt>-nostartfiles</tt>) which disables the "start files" <tt>crt*.o</tt> that areis normally automatically added to the link command line. By passing <tt>-nostartfiles</tt>, we promise to the compiler that we take on the responsibility ourselves to call the "program initialization tasks" in the <tt>crtbegin.o</tt> and <tt>crtend.o</tt> files. This means as we need to manually add <tt>crti.o</tt>, <tt>crtbegin.o</tt>, <tt>crtend.o</tt>, and <tt>crtn.o</tt> to the command line. Since we provide <tt>crti.o</tt> and <tt>crtn.o</tt> ourselves, that is trivial to add to the kernel command line. However, <tt>crtbegin.o</tt> and <tt>crtend.o</tt> is installed inside a compiler-specific directory we'll need to figure out the path. Luckily, gcc offers an option just to do this. If <tt>i686-elf-gcc</tt> is your cross-compiler and <tt>$CFLAGS</tt> is the flags you would normally provide to your compiler, then
 
<source lang="bash">i686-elf-gcc $CFLAGS -print-file-name=crtbegin.o</source>
Anonymous user