Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need for C startup routine?

Quoting from one of the unix programming books,

When a C program is executed by the kernelby, one of the exec functions calls special start-up routine. This function is called before the main function is called. The executable program file specifies this routine as the starting address for the program; this is set up by the link editor when it is invoked by the C compiler. This start-up routine takes values from the kernel the command-line arguments and the environment and sets things up so that the main function is called as shown earlier.

Why do we a need a middle man start-up routine. The exec function could have straightway called the main function and the kernel could have directly passed the command line arguments and environment to the main function. Why do we need the start-up routine in between?

like image 518
nitin_cherian Avatar asked Dec 01 '22 09:12

nitin_cherian


2 Answers

Because C has no concept of "plug in". So if you want to use, say, malloc() someone has to initialize the necessary data structures. The C programmers were lazy and didn't want to have to write code like this all the time:

main() {
    initialize_malloc();
    initialize_stdio();
    initialize_...();
    initialize_...();
    initialize_...();
    initialize_...();
    initialize_...();

    ... oh wow, can we start already? ...
}

So the C compiler figures out what needs to be done, generates the necessary code and sets up everything so you can start with your code right away.

like image 130
Aaron Digulla Avatar answered Dec 06 '22 10:12

Aaron Digulla


The start-up routine initializes the CRT (i.e. creates the CRT heap so that malloc/free work, initializes standard I/O streams, etc.); in case of C++ it also calls the globals' constructors. There may be other system-specific setup, you should check the sources of your run-time library for more details.

like image 45
zeuxcg Avatar answered Dec 06 '22 10:12

zeuxcg