c-compilation and how it works!

When we refer to compilation, we often do not think about the work behind it, since the compiler is the “tool” that allows us to interact with the machine. Each line of our source code must be interpreted by the machine through the copier for its use.
In this blog we will explain a little, how this process works and we will take the c language as a reference.
C IN UBUNTU BASH
These are the most useful options to perform the compilation through our terminal in ubuntu (linux):
- -c
It performs a preprocessing and compilation, obtaining the file in object code, which as its name says the preprocessing is a previous preparation for the translation of the code.
- - E
Preprocess the code and send it ready for standard output
- -o
Indicates the name of the output file and defines it without importing the stage in which it is or has been completed within the compilation
- -l
Specify the path to the directory where the files to be included in the program are located and source code
- -L
Specifies the path to the directory where the library files with the code object of the functions in the program with the source code are located.
- -Wall
Help with displaying the error or warning messages of the copier.
- -g
Includes in the generated executable the information to trace errors using a debugger
- -v
Shows the commands executed at each step of the compilation and its version of the compiler with details.

COPILATION STEPS
the compilation process is defined in 4 stages: preprocessing, compilation, assembly and linking. To pass a program written in programming language to an executable understood by the machine, it is necessary to carry out the 4 stages in order.
PREPROCESSOR
Directives to the preprocessor are interpreted. #define variables are substituted in all places with their names
we can preprocessed our code with this command steps:
To understand it better we first look at the content of the test program, then we preprocess it with gcc -E and we can see the preprocessed code and its changes
$ gcc -E main.c


COMPILER
The compilation transforms the c code into our own processor language.
For this process we use the gcc -c command to convert our preprocessed main.c to compiled
$ gcc -S main.c

we can see the new file created and its content with:
$ more main.s

ASSEMBLER
Transforms the program written in assembly language to object code, a binary archov in executable machine language.
Assembly is named as:
$ as -o main.o main.s
create a new object file main.o with main.s

LINKER
this linking stage is where one or more modules in object code are joined with the existing code in the libraries.
is called with ld.
$ ld -o fileFinal main.o -lc
but it is more frequent to use gcc -o to test the object codes directly
$ gcc -o fileFinal main.o

finally we have our machine code ready and compiled.
very useful to understand the operation of our copier with this example in C with the linux terminal.
by: Luis Carvajal