Steps of compilation in C

Julian Villegas
Basics Full Stack Engineering
3 min readSep 19, 2019

In C Programming Language, the process can be split into four separate stages: Preprocessing, compilation, assembly, and linking.

Tomado de: https://miro.medium.com/max/476/1*E_gsbq_A5vIUYxLMc7IUtg.png

1. We have to write our source code from any editor, i recommend emacs or vi on Linux. Here is an example.

Example of C code

After finish it, you have to save your file with .c extention

2. The nextstage of compilation is called preprocessing. In this stage, lines starting with a # character are interpreted by the preprocessor as preprocessor commands.

We’ll use the gcc compiler

  • To print the result of the preprocessing stage, pass the -E option to gcc. Let’s see.
Preprocessor
  • It generates an output in a file called “c”and the preprocessor will produce the contents of the <stdio.h> header file joined with the contents of the c file, it delete its leading comment. Let´s readthe file with tail command.

3. Compilation. In this stage, the preprocessed code is translated to assembly instructions specific to the target processor architecture. These form an intermediate human readable language.

  • To save the result of the compilation stage, pass the -S or -c option to gcc:
  • This will create a file name with .s extention, containing the generated assembly instructions.

4. Assembly. During this stage, an assembler is used to translate the assembly instructions to object code. The output consists of actual instructions to be run by the target processor.

  • To save the result of the assembly stage, pass the -S option to gcc:
  • Running the above command will create a file name with .o extention, containing the object code of the program. The contents of this file is in a binary format.

5. Linking. The object code generated in the assembly stage is composed of machine instructions that the processor understands but some pieces of the program are out of order or missing. To produce an executable program, the existing pieces have to be rearranged and the missing ones filled in. This process is called linking.

--

--

Julian Villegas
Basics Full Stack Engineering

Professional System Engineer and Student at Holberton School Colombia