What happens before main in C++?

A lot depends on the execution environment. A great deal of work may be done by the operating system loader before the C run-time start up that is specifically part of your executable runs. This operating system dependent part of setting up the execution environment is common to all native (machine language) executables, regardless of source implementation language.

What part is played by the OS and what is performed by code that is part of your executable differs depending on the execution environment. The OS loader (in a non-standalone system)is responsible for loading the code into memory, and may involve loading and linking dynamically-linked libraries (DLL or shared-libraries depending on the OS nomenclature). Regardless of whether it is an OS or an C-runtime responsibility, the following normally occur:

  • Establishment of a stack
  • Zero initialisation of initialised static data
  • Initialisation of explicitly initialised static data
  • C library initialisation (typically stdio and heap-management require some initialisation)
  • For C++ call static constructors.
  • Creation of the stack frame for main() (argv, argc parameters)

In GCC and some other compilers for example, the part that is performed by your program rather then the OS prior to your program starting, is performed by a separately linked module called crt0.o. This is normally written in assembler and is automatically linked by default.

For further examples and discussion see:

Leave a Comment