Social Icons

Thursday, July 17, 2014


In the last article we have seen the exact use of the runtime code. Now, lets implement this runtime code. In this article we will write our own runtime code and append it to the program code. We will tell the linker not to append the default start up files, instead use our own runtime code.

In the below example I am going to write a program with my own runtime code. The program is as follows:-

Here I have written my own runtime code. The actual implementation of the runtime code will be different. What I have done in this program is just calling the functions in the order it happens it default runtime code. The actual implementation of the _fini, _init, and _start will be different. The fini is used form termination of the process and perform a cleanup operation. Now lets execute this program using the Gcc compiler.
Now go through each line of the above image. If you observe carefully, you can see that the compiler throws an error saying that there are multiple definitions of "_start", "_fini".  This error is thrown because the we have already appended the runtime in our functionality and the linker also tries to append the runtime code into our object file which throws an error. Hence, we must tell the linker that it need no to append the startup code or the runtime code. How do we do it????? Lets look into the man pages for help.
In the man pages of the Gcc compiler if you search for the linker options you can see an option called -nostartfiles. Using this option we are telling the linker do not append the runtime code into my object files. Now lets compile the program using this option -nostartfiles.

I have compiled the program with the flag -nostartfiles and successfully executed the program. The output gives you the clarity of how the runtime code is executed. The function calling is very clearly shown in the output.

This is how a program which is loaded into the memory will get executed. The program which we write is inside the main function and the main function calls all the other functions which we write in our .c file. The main function is called by the start function. In my next article we will learn about the stack data structures and libraries.

No comments:

Post a Comment