GCC : A Compilation Recipe

Photo by Nikhil Mitra on Unsplash

is a compiled language, therefore anything you write (source code) goes through a series of process in order to have your executable code. I like to think of it like a recipe, you have to go step by step in other get your exquisite code done. Let me show you how to cook a compiled code.

After you have finished your source code you have to pass it through the compiler, in this case GCC (GNU Compiler Collection).

Command to compile file “main.c”

Now lets break this down, the compiler goes through 4 steps before plating out your program (compiled file). First step is the Preprocessor, this will search for headers (#include) and macros (#define) in code and expand them. If you want to stop the compiler at this first step, here is how you would do it:

Secondly expanded code will go through the Compilation process. In this step the compiler compiles the output from the preprocessor step into an assembly code for a specific processor. Just like before if you wish to stop the compilation process at this step you will need to flag it. If done, you will be generating a another file with the same name as your main file but with the extension “.s” . Let’s see below:

main.s file, midway level language between humans and machine

Third step is the Assembly process, basically converts your file into machine code(zero and one) AKA binary code. The flag to stop the compiler is “-c” and it will output your file with the extension “.o”

Command to stop gcc at assembly and output
Command to stop gcc at assembly and output
Command to stop gcc at assembly process and its output

Final step will be the Linking process, this will take the object file (main.o) and link it with a library function needed. Finished product will be an executable file “a.out” by default if given no output filename. If you would like to rename your executable file give it this option “-o” at gcc.

Executable file by default = “a.out” vs Executable file -o [option] filename = “hello”

Now lets look at the finished program:

If you have enjoy this blog, please share and leave a comment on how can I improve this blog or on any topic you will like to write on. Thank you for taking the time to read me.

Reference:

Kryukova T. (2017) ‘The Magic Black Box of GCC Explained’, Medium, 17 May. Available at: https://medium.com/@tyastropheus/the-magic-black-box-of-gcc-explained-54f991f4f6a2#:~:text=There%20are%20four%20steps%20in,in%20order%20to%20execute%20it. (Accessed: 4 February 2021).

(2018) ‘GCC and Make Compiling, Linking and Building C/C++ Applications’, ntu.edu.sg, March. Available at: https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html . (Accessed: 4 February 2021).

Currently Holberton Student, aspiring nomad programming life