What happens when you run “gcc main.c”?
When you run
gcc main.c, what will happen is that an executable file named a.out will appear in the directory you are in. What happens in between the time that you run the command and receive the executable?
The image above shows step by step what happens when running the
gcc command. On the very right side, we can see that running the command
gcc main.c will give us a file called a.out (assuming in our current directory, we have a
main.c file with c code in it). To the left of this, we have the four steps of process: preprocessor, compiler, assembler, and linker.
Preprocessor: What this step does is that it takes our source code (in this case, it is main.c) and firstly it removes all comments from the code. After that it will include header file codes (
#include on the top) into the source code. The image on the bottom shows what comments (dark blue font) and header file code (
#include on top) look like.
Compiler: After the preprocessor hands over the processed code over, the compiler then translates the source code into an assembly code. Which is instructions defined in English, such as printf.
Assembler: Once the source code has been translated into assembly code, the compiler hands it off to the assembler. What the assembler does is that it converts the assembly code into object code, which is better known as binary code (0s and 1s). Binary code is language that computers can understand. To recap: after the source code (main.c) has had it’s comments removed and header files included, it gets translated into an assembly code (English defined instructions such as printf). After it has turned into an assembly code, it gets converted into object code (binary code).
Linker: Lastly, the assembler hands off the object code to the linker, and what the linker does is that it links the libraries it has with the object code. An example of a library would be the square root function (
sqrt), which comes from the C math library (
After all of that; from source code to processed source code, to assembly code, to object code, to linking the libraries to the object code. An executable file will appear in your directory after running the command
gcc main.c , as shown below (using the c code from the image above):