Compiling a C program:-
C is a high level language and it needs a compiler to convert it into an executable code so that the program can be run on our machine.
How do we compile and run a C program?
Below are the steps we use on an Ubuntu machine with gcc compiler.
- We first create a C program using an editor and save the file as filename.c
$ vi filename.c - Then compile it using below command.
$ gcc –Wall filename.c –o filenameThe option -Wall enables all compiler’s warning messages. This option is recommended to generate better code.
The option -o is used to specify output file name. If we do not use this option, then an output file with name a.out is generated. - After compilation executable is generated and we run the generated executable using below command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to become an executable:
- Pre-processing
- Compilation
- Assembly
- Linking
By executing below command, We get the all intermediate files in the current directory along with the executable.
$gcc –Wall –save-temps filename.c –o filename
Pre-processing
This is the first phase through which source code is passed. This phase include:
- Removal of Comments
- Expansion of Macros
- Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i: using $vi filename.i
Analysis:
- printf contains now a + b rather than add(a, b) that’s because macros have expanded.
- Comments are stripped off.
- #include<stdio.h> is missing instead we see lots of code. So header files has been expanded and included in our source file.
Compiling
The next step is to compile filename.i and produce an; intermediate compiled output file filename.s. This file is in assembly level instructions. Let’s see through this file using $vi filename.s
Assembly
In this phase the filename.s is taken as input and turned into filename.o by assembler. This file contain machine level instructions. At this phase, only existing code is converted into machine language, the function calls like printf() are not resolved. Let’s view this file using $vi filename.o
Linking
This is the final phase in which all the linking of function calls with their definitions are done. Linker knows where all these functions are implemented. Linker does some extra work also, it adds some extra code to our program which is required when the program starts and ends. For example, there is a code which is required for setting up the environment like passing command line arguments. This task can be easily verified by using $size filename.o and $size filename. Through these commands, we know that how output file increases from an object file to an executable file.
No comments:
Post a Comment