How to compile your C source code

If you are a software developer, you should know something about C programming language. Here, we going to learn, how you can compile your C source code from the terminal.

If you use to use some IDE to code, maybe you don’t know that before you can execute your code, there is a compilation process. GCC is the main compiler for C/C++ language but before we use gcc commands, let’s understand how compilation process works.

Compilation process in C

Before you can execute your C code, there is some steps your GCC done before. Let’s see this in a nutshell.

After you write your source code, GCC compiler re writes your code and preprocess. In preprocess step, all your comments are removed. Now, compiler converts your C code to Assembly code (this step is compile step), so after this, GCC creates an .s file. The next step is assemble your Assembly code to Binary code (so your computer can understand). So, when you assemble, this process creates other new .o file. Now the last step is called “link”. That’s because when you code a big project, you usually don’t have just one .c file. You should have a lot of .c files. So, after you preprocess, compile, assemble all those files, your compiler has to link all those file in just one executable file. So, now you get one executable file for all your C code.

compilation process step by step

As I told you before, this is all compilation steps were explained in a nutshell. I encourage you to visit this website (Compiling a C program:- Behind the Scenes) if you want to know deeper what exactly happens in each step.

Now I want to teach you how you can execute each compilation step. At this point, if you have not installed gcc compiler, you should it now. Just type $sudo apt install gcc . It should be enough to get all gcc tool in your terminal.

Let’s start with the preprocess step. If you want just preprocess your code but no compile, no assemble, no link, there is a specific flag to gcc command. $gcc -E yourfile.c If you use -E flag, GCC compiler will preprocess your code but don’t compile. To preprocess and compile your code you use -S flag, so your command looks like $gcc -S yourfile.c But now, if you want preprocess, compile and assemble you can use -c flag in your command. So after you execute $gcc -c yourfile.c it gives you an output file with .o extension. Finally to do all steps with just one command, use only $gcc yourfile.c and GCC compiler will do everything for you, and gives an executable file.