Compilation Steps in C Program: Pre-processing, Compilation, Assemble, Linking

In this tutorial, we will learn the compilation process of the C Program in detail and understand the intermediate files generated during the compilation process.

Understanding about the Compilation?

Converting the high-level language source file into a low-level machine-readable format is called compilation. It checked the syntax and structural error of the source file and generate the object code.

Let’s start the compilation process with a simple hello world C program.

 

/* Learning C compilation step*/
#include<stdio.h>
int main()
{
	printf("Hello World !");
	return 0;
}

To Compile the above program run the below command.

$ gcc -save-temps hello.c -o hello

-save-temps flag is used to save all the intermediate files during compilation.

hello.i (Generated by Pre-processr)

hello.s (Generated by Compiler)

hello.o (Generated by Assembler)

hello (Generated by Linker)

Four Stages of Compilation Process in C Program

There are four steps to compile the c program and generate the executable binary.

  1. Pre-processing
  2. Compilation
  3. Assemble
  4. Linking

Compilation Step

Pre-processing

The first step of compilation is called preprocessing.

  • Lines starting with a # are interpreted by the preprocessor
  • Removal of Comments form source code
  • Expansion of Macros
  • Expansion of the included files

$ gcc -E hello.c -o hello.i

Compilation

The second step is called compilation.

  • The preprocessed code is translated to assembly instructions.
  • Verify the C program for syntax errors.
  • Translate the file into intermediate code i.e. in assembly language.

$ gcc -S hello.i -o hello.s

Assembly

In this step, Assembler is used to translate the assembly instructions to object code.

$ gcc -c hello.s -o hello.o

Read the binary file by using the following commands:

$ objdump -D hello.o

$ hexdump hello.o

At this stage only existing code is converted into machine language, the function calls like printf() are not resolved.

Linking

This step links the generated object file with a standard library and generates the final executable file.

  • appending bootstrap code
  • linker assigned the load address to executable
  • Linux executable file called .elf
  • windows executable called .cof

$ gcc hello.c -o hello

 

Add comment


Security code
Refresh