Process of compiling in C (ex. gcc main.c)
You have some program in C, lets call that main.c, and you want run that program. And when you try to run that program, it doesn’t work. First things first, you should ask yourself if you have compiled your main.c. This is exactly what ‘gcc main.c’ does, but in this post I will explain the nitty gritty on what happens to your main.c file during compilation.
1. You wrote a main.c file!
This will be referred to as the source file from now on.
2. The start of compilation: Preprocessor
The first step after you type in ‘gcc main.c’ is that your code goes through the preprocessor. What the preprocessor does is it expands your source file.
a) first, removes any comments in your code
b) second, include (print out) all the code for all header files you have. In our case, it is the stdio.h file.
c) generates any macros you have used and replace symbolic content defined using #define with their values.
After that is all done, your new file is a temporary file (but still can be printed using -E flag with gcc) that will go to the next stage. Below you can ignore the command I have used, but I have basically printed out the last ten lines of the temperary file.
3. Second Step: Compiler
This temporary file will then be compiled into assembly lanuage for any platform. What this just means is that it will be translated into instructions of what your platform should do. These instructions are defined in english and are called mnumonics. This will produce a file with the same name as your original file but with a ‘.s’ extenstion. So in our case, it will be called ‘main.s’. This file is also called the assembly code.
4. Third Step: Assembler
The assembly code then go through the Assembler which coverts the assembly code to object code. Basically what it is doing is that it converts the assembly code to machine language (i.e binary) for the platform to understand, since computers clearly cannot understand english. This object code has the same name as your original file but with a .c extension.
5. Final Step: Linker
So you have your object code (main.o) for main.c. The last step is to link your code. Because our main.c program is so simple, there isn’t anything to link. However, imagine you have a program that uses other c programs and libraries. What the linker does, is that it takes all the libraries and object code from the other c programs and links them all together to a single executable file (a.out). So when you run your main.c into your gcc compiler, it should create an executable file called a.out.
Now you have an execuatable file and you can run your program with ./a.out. If you are curious, you can change the name of a.out using a gcc flag (-o). Example below: