Compilation process in C
C language that first appeared in 1972 and its origin is linked to the development of the Unix operating system. C is called a low-level language because of its approach to machine coding.
There are compiled and interpreted programming languages. C is a compiled language, it means that files written in C must be compiled before being executed and here we will learn how to do it.
Let's get started. For the compilation process I will use a Linux Ubuntu 20.04.2 operating system and gcc as compiler.
The build process has four steps:
- Preprocessor
- Compiler
- Assembler
- Linker
For a better illustration, I'll use this source code written in C:
- Preprocessor: The preprocessor replaces the #include <stdio.h> line with the header file. In this header the printf() function is declared. Specifically #include will be replaced by the full content of the file stdio.h.
To run only the preprocessor, use the command gcc -E file_name.c -o file_name.i. The output of this command is stored in a file with an .i extension.
The code looks like this:
- Compiler: The compiler takes the preprocessed file and converts this code into assembly code.
To run the compiler, use the command gcc -S file_name.c. The output of this command is stored in a file with the extension .s and will have the same name as the source file by default.
The code looks like this:
- Assembler: The assembler takes the assembly code and transforms it into object code, that is, code in machine language (binary).
To run the assembler, use the command gcc -c file_name.c. The output of this command is stored in a file with the extension .o and will have the same name as the source file by default.
The code looks like this:
- Linker: The linker creates the final executable file in binary code and is also responsible for linking other associated programs.
To run the linker, use the command gcc file_name.c no options. The output of this command is stored in a file called a.out by default.
But you can also create the executable file with any name by adding -o new_name to the above command.
In any case, every time you run the command, the executable file with the same name is overwritten.
The code looks like this:
It should be noted that it is not necessary to execute each of the steps to obtain the executable file. Just use gcc file_name.c and the compilation process is complete.
Execution: To execute the file, use ./name_file and that's it.
Done, we have learned the compilation process in C and how it works.
By: Carolina Lopera
Holbie - Cohort 15