What happens when you type gcc main.c
Although using gcc to compile C programs gives you an executable in no time, there is a process that the gcc compiler goes through in order to make the executable.
When you gcc, four things happen: preprocessing, compilation, assembly, and linking.
The first step before compilation is that the c file is processed by the preprocessor. This is done by a whole different program called cpp, but it is automatically executed when you gcc. During this process, the preprocessor modifies the code you gave it into different code that is either stored in memory or created into a file.
To see it stored as a file, you can enter the following:
gcc -E -o <FILE> <FILENAME2>
If you have an #include at the top of your file, the preprocessor pastes everything from <stdio.h> into the new preprocessed file; it would also expand any #define. The preprocessor also removes comments and replaces macro names with code.
For this post, I created a c file called hello.c. After I run the command above, my terminal now shows the creation of the file labeled as hello.p:
After the preprocessor is done with its task, the compiler can compile the program by turning the C code into an assembly code file which ends in “.o” which now contains the code in assembly.
To convert the file from the preprocessor to just compile, you could do the following:
gcc -S <FILE>
After I entered this command, the hello.s file is created and is displayed below:
The assembler converts the assembly code into object code, which is code in complete binary meant for the machine.
You can change the assembly code into object code:
gcc -c <FILE>
When I did the above, you get the following where the new file is listed as hello.o:
The last step of the process is to create an executable using gcc is the linker. The linker merges all the object code into a single file, and it will also link code to libraries.
After all these steps, it will finally create an executable.
Although you could just do gcc <FILE> to get the final executable, it is a lot more helpful to go through each process to get a fundamental understanding of what is happening in the terminal.