Compilation Process In C

Hey folks in this article we will explain compilation process in C how does our program is translated to machine code that can be executed in our machine 

Compilation process

What is compilation ?

Compilation is a process of converting source code written in high-level languages such as C or C++ into machine language code that can be executed by the processor

Compilation process in C can be divided into four stages.

  • Pre-processing
  • Compiling
  • Assembling
  • Linking

Pre-processing Stage

This step is done using a program called pre-procesor .The pre-procesor takes the source code as an input , remove all comments from the source code and interpret all pre-processing directivese .

For example if the pre-procesor find this line in our code  #include <studio.h> it replaces this line with content of the file studio.h

The pre-procesor generate output files with .i extension 

to learn more about pre-procesor and pre-processing directivese see this article.

Compilation stage

After expanding the code in the pre-processing Stage the output file is then passed to a program called The Compiler. The Compiler converts input file into assembly language code that is only understandable by the specific hardware target .

The Compiler generates an output file with .s extension


Assembling Stage

This stage is done using a program called assembler which read the assembly code from the input file .s and converts it to machine language code with some other object code that only understandable by the linking stage 


Linking Stage

Mainly all programs written in c uses library functions .

These library functions are pre-compiled and the object code of these library files is stored with .lib or .a extension.

The main working of the linker is to combine the object code of library files with the object code of our program .

Sometimes a situation arises ( all the time actually ) when our program refers to functions defined in other library files . It links the object code of these files to our program .

Therefore we conclude that the job of the linker is to link the object code of our program with the with the object code of the library files and other files in our program 

Note : every .c file in our project is Passed individually throughout the first three stages ( pre-processing , compiling , assembling ) 

Linking stage is the only stage that all objected files are readed together .

Another Note : the object code not only contains machine code but also contains symbols of functions used and needed to be linked with the library files or other files in the project.


References & Further Reading :

Compilers

C programming language