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:

  • Linux x86 Program Start Up
  • Typical stand-alone embedded system start-up

Question 1- What's that entity that does this stuff? Who writes it?

The C compiler team writes it.

What happens is OS specific but basically it does things like deal with command line arguments, open/connect stdin, stdout, stderr, etc..

If you dig around the gcc or clang source I'm sure you can find the code1. You can pass in options to the linker to not include this code if you program doesn't need it. For example if you don't read arguments nor use files and you want to do whatever other setup yourself you can pass in arguments not to include the startup code.

Question 2- Are there additional things in C++?

Yes, there's no such thing as constructors and destructors in C so if nothing else C++ has to deal with those.

1: here's an example

Tags:

C++