GCC process breakdown
Introduction:
In some programming languages like C you need to compile your code in order to be executed, I would like to begin this article with the following question:?
Why do we need to compile our code??
This is necessary because the computer only understands “machine language” and this is nothing more nothing less than binary numbers, ones and zeros.?
So the compiler “translates” the high level code to numbers that the computer can understand.
GCC is a widely used compiler and stands for: GNU?Compiler?Collection.
GCC breakdown:
There are four steps
Compiling process explained with an example:
Create a file named: "compiling.c" with the following code inside:
#include <stdio.h>
/* Holberton school project */
int main (void)
{
? ? ? ? printf("This is how you compile a file\n");
? ? ? ? return (0);
}
Step 1 (preprocessing): if we just want to preprocess the code, we need the "-E" flag of gcc. For example if we want to preprocess the compiling.c program created earlier into a file named "test_file" we need to use the following code:
gcc -E compiling.c > test_file
We can use the linux command "ls" and see the files and directories inside "tests" as you can see there is a file named "test_file" containing the pre-processed code of "compiling.c".
Step 2 (compiling): ?compiler reads the preprocessed data and generates its equivalent assembly code. In gcc this can be done with the flag “-S”. Let’s see below the complete command:
gcc -S compiling.c
We have successfully created de compiled file "compiling.s" and we changed our source code into assembly language. It is important to clarify that when step 2 is executed, step 1 must first be carried out, therefore when we did the compile step, the preprocess step was also carried out.
Step 3 (assembly): As it was stated before the assembler processes the assembly code generated by the compiler and generates Object files (.o file with gcc). This generate the machine code.
To generate the object files we use the the following command:
gcc -c compiling.c
Now we have a file called "compiling.o" with the binary code.
Step 4 (linking): last but not least the linker, links all the object files that we give with the executable and if we use libraries the linker will extract and connect them to object file. Then creates the final executable.
By default the linking command generates "a.out" executable but with the "-o" flag we can choose the name we prefer.
gcc compiling.c -o compiling_test
Finally there is our executable file "compiling_test". Now we can run our executable:
I hope you enjoyed the article, thanks for reading!
Good to read how fellow students approach these tasks... well done from the Melbourne Cohort in Australia
Good job! ??
Economista- Platform Experts & Process Team Lead en Rocket Lab | Mobile App Growth.
3 年Muy bueno!!