Runtime
Overview
The C runtime is a collection of object files provided by the compiler toolchain. It contains functionality that wraps around the actual invocation of main. Namely, the following files are included:
crt0.oorcrt1.o(the number indicates the ABI version)crti.o(used for partially constructing the .init and .fini sections)crtn.o(used for partially constructing the .init and .fini sections)
The _init and _fini functions are assembled by the linker in three parts:
- The function prologues are built from
crti.o - The body is built from linked objects
- The function epilogues are built from
crtn.o
The .init_array and .fini_array sections supersede the .init and .fini sections respectively.
Startup
The main function is typically described as the special function serving as the entry point to C programs. Though this is not technically true, from a practical perspective it is true enough. It can have several different prototypes, but the following two are always possible:
int main(void);
int main(int argc, char* argv[argc+1]);
The only two return values guaranteed to work on all platform is EXIT_SUCCESS and EXIT_FAILURE. Reaching the end of main is equivalent to a return with value EXIT_SUCCESS.
In hosted environments, a third argument char *envp[] is included. This points to a null-terminated array of pointers to char, each of which points to a string encoding an environment variable as NAME=value.
Shutdown
Returning from main is semantically equivalent to invoking the exit function. On exit, any functions registered with atexit are called in reverse order of registration. A number of cleanup operations (e.g. closing open file descriptors, flushing buffers, etc.) are also performed.
_Noreturn void exit(int status);
Other termination functions exist:
quick_exit- Functions registered with
at_quick_exitare called in reverse order. - Other cleanup operations are implementation-defined.
- Functions registered with
_Exit- No functions registered with
atexitorat_quick_exitare run. - Other cleanup operations are implementation-defined.
- No functions registered with
Unlike the above three, abort can be used to cause abnormal program termination.
_Noreturn void abort(void);