What happens when you type gcc main.c ?
Juan Uribe
Software Developer | Node.js & React.js | Database Architect (PostgreSQL, MongoDB) | Cloud & Microservices Specialist
GCC is an integrated compiler of the GNU project for C, C++, Objective C and Fortran. This compiler is capable of receiving code from these languages and generates a binary executable program in the language of the machine where it will work. GCC stands for (GNU COMPILER COLLECTION) and until today it is still used for this functionality.
So basically, a compiler is a translator that transform a program into a language that machines can understand. The compilation has a series of steps to get an executable file, these steps can be make it individual or all in one step. In this post will work again on Linux, so the compilation can be done by commands.
The steps that compiler does...
- Preprocessing
- Compilation
- Assembly
- Linking
Prepocessing:
At this stage the #define variables are interpreted and replaced where they were called.
Above we have a program in C with a sum a constant named A, that makes a sum between A and b, and prints the result in sum, we will do the preprocessing stage to prove the statement above:
That command make the preprocessor, lets see what happens behind...
As I said before, the preprocessor replaced the #define variables, we can see the below that its happens:
Executing the command cat, we can see within the pre-example file first show what's in "<stdio.h>" (a lot of functions) and later replace all #define (constant variables, in this case).
Compilation:
Compilation transforms C code into assembly language, in that way the machine can understand the code. WE use the same example to do the step, using the this command we can produce the assembler code "gcc -c example.c"
Using cat to explore inside the file, we can see the assembler code:
Assembly:
The assembly transforms the assembly language into a object code, using the command "gcc -S example.c" we can make the assembly step:
Note: if you use the command above, a .s extension is created within that file is the object code.
Linking:
This step incorporates the object code in some executable file, using the command "gcc example.c -o exe-example", lets see below:
The file created was exe-example and we can execute using the next syntax "./file_to_execute".
You could see the compilation process, most of the time you only need the executable file, but if you have an issue, maybe checking with some of those steps you can find the issues.