What happens when you type gcc to compile a .c file?

Ana-Morales
3 min readJun 11, 2020

GCC is an integrated compiler of the GNU project for C, C ++, Objective C and Fortran; it is capable of receiving a source program in any of these languages and generating a binary executable program in the language of the machine where it has to run.

The acronym GCC stands for “GNU Compiler Collection”. Originally it meant “GNU C Compiler”; GCC is still used to designate a C build. G ++ refers to a C ++ build.

Stages of the compilation process

To carry out the compilation process, four successive stages are covered: preprocessing, compilation, assembly and linking. With this, it is possible to go from a source program written by a human to an executable file. The gcc command can perform the entire process at once.

Let’s see the result of each stage compiling the following example1.c program:

1. Preprocessing

In this first stage the preprocessor directives are interpreted. The lines in the code that begin with the “#” character are preprocessor directives. Tasks such as text substitution, stripping of Comments, file Inclusion are performed in this stage.

We can get the result of this stage with the option -E for the gcc command. We are going to save the result in a file named example1.i

Now let’s see the firts lines of the resulting preproccessed file

2. Compilation

The compilation transforms the C code into the assembly language specific to the processor of our machine.

We can get the result of this stage with the option -S for the gcc command. By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s, so the resulting file is named example1.s

This is how the result of this stage looks like:

3. Assembly

The assembly transforms the program written in assembly language to object code, a binary file in machine language executable by the processor.

We can get the result of this stage with the option -c for the gcc command. By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o, so the resulting file is named example1.o

This is how the result of this stage looks like:

4. Linking

The C / C ++ functions included in our code, such as printf () in the example, are already compiled and assembled in existing libraries on the system. It is necessary to somehow incorporate the binary code of these functions into our executable. This is what the link stage does, where one or more modules are brought together in object code with the existing code in the libraries.

All the previous process (the four stages) can be done in one step by gcc when invoked as follows:

It produces an executable file ‘a.out’. If we execute it we get the following:

--

--