Jump to content

crt0

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by FUZxxl (talk | contribs) at 11:11, 25 December 2017 (→‎Example crt0.s: _start calls exit, not the _exit system call as it too needs to do all the things exit does, like flushing buffers or calling atexit(...) function.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

crt0 (also known as c0) is a set of execution startup routines linked into a C program that performs any initialization work required before calling the program's main function. It generally takes the form of an object file called crt0.o, often written in assembly language, which is automatically included by the linker into every executable file it builds.[1]

crt0 contains the most basic parts of the runtime library. As such, the exact work it performs depends on the program's compiler, operating system and C standard library implementation.[1] Beside the initialization work required by the environment and toolchain, crt0 can perform additional operations defined by the programmer, such as executing C++ global constructors and C functions carrying GCC's ((constructor)) attribute.[2][3]

"crt" stands for "C runtime", and the zero stands for "the very beginning". However, when programs are compiled using GCC, it is also used for languages other than C. Alternative versions of crt0 are available for special usage scenarios; for example, the profiler gprof requires its programs to be compiled with gcrt0.[4]

Example crt0.s

This example is for linux x86_64 with at&t syntax.

.text

.globl _start

_start: # _start is the entry point known to the linker
    mov %rsp, %rbp    # setup a new stack frame
    mov 0(%rbp), %rdi # get argc from the stack
    mov 8(%rbp), %rsi # get argv from the stack
    call main         # %rdi, %rsi are the first two args to main

    mov %rax, %rdi    # mov the return of main to the first argument
    call exit         # terminate the program

See also

References

  1. ^ a b "The C Runtime Initialization, crt0.o". embecosm.com. 2010. Retrieved 2013-12-30.
  2. ^ "Program initialization: Creating a C library". osdev.org. 2014-02-25. Retrieved 2014-04-21.
  3. ^ "Calling Global Constructors". osdev.org. 2014-04-08. Retrieved 2014-04-21.
  4. ^ "Compiling a Program for Profiling: GNU gprof". sourceware.org. Retrieved 2013-12-30.