Compilation Contemplation
Before using any C program, it is essential to first compile it. While a simple
gcc main.c
will compile your code for you, it’s critical to understand the steps that it takes to make your program executable.
Steps of Compilation
- Preprocessor
- Compiler
- Assembler
- Linker
Preprocessor
The preprocessor will format your program for the compiler. To do so, it removes comments, includes header files, and performs macro expansion.
To send a file to the preprocessor but not compile it, we will use this command:
gcc -E [filename.c]
Compiler
The compiler takes the output from the preprocessor and turns it into assembly code.
To compile our file but not assemble it, we will use this command:
gcc -S [filename.c]
If we apply this to our main.c file, we get this output:
vagrant@vagrant-ubuntu-trusty-64:~/holbertonschool-low_level_programming/testdir$ gcc -S main.cvagrant@vagrant-ubuntu-trusty-64:~/holbertonschool-low_level_programming/testdir$ lsmain.c main.s
Assembler
The assembler takes the assembly code and turns it into machine code.
To send our file through every step except for the linker, we will use this script:
gcc -c [filename.c]
if we apply this to our main.c file, we get this output:
vagrant@vagrant-ubuntu-trusty-64:~/holbertonschool-low_level_programming/testdir$ gcc -c main.cvagrant@vagrant-ubuntu-trusty-64:~/holbertonschool-low_level_programming/testdir$ lsmain.c main.ovagrant@vagrant-ubuntu-trusty-64:~/holbertonschool-low_level_programming/testdir$
You will notice that this gives you the file main.o. While this format is the same as a fully-compiled program, it will not be executable.
Linker
The linker combines the object code from the assembler with library code in order to produce an executable program.
To fully compile our program, we will use this command:
gcc [filename.c]
As you’ll notice, this command will automatically name the file for you. If you want to specify the new name of the file, use this:
gcc [main.c] -o [main]
You will now have an executable file!