What Happens When You Execute gcc main.c?

Adam Taylor
3 min readFeb 11, 2021
Small diagram showing the steps of compilation in C

First off, what exactly is gcc and how does it work?

Gcc, also known as the GNU Compiler Collection, is an integrated distribution of compilers for several major programming languages, including C. Gcc performs the compilation step to build a program, and then it calls other programs to assemble the program and to link the program’s component parts in an executable program that you can run. The compilation is performed in four sequential phases by the compilation system (a collection of four programs — preprocessor, compiler, assembler, and linker.)

The first step is preprocessing.

The preprocessor is invoked automatically by the compiler and it’s job is to remove all of the comments from our program main.c. It will then include code from the header and source file before it replaces any macros that we used in our program with code.

The second step is compiling.

This is when the actual compilation of our program will take place. What happens during compilation is gcc will convert the preprocessed code to assembly language. The assembly code generated is particular to the instructions et of the processor, or CPU, instead of your computer. Assembly code is basically a human readable form of machine language, which includes variable names and conversion of bytes sequences to strings to improve readability.

The third step is using the assembler.

The assembler accepts the output of the compiler and turns it into machine code: an executable binary file that contains instructions that the CPU in your computer will understand. The output of the assembler is put in a file called main.o. This is what is fed to the final stage of the compilation process, the linker.

The fourth step is linking.

The linker will accept the main.o file and it also will accept any pre-compiled libraries that were imported using the #include preprocessor directive. It then will continue to merge the necessary parts to make a standalone executable binary. The linker should only link the functions out of the included libraries that you were actually using, such as printf for example. You are able to use something called a compiler flag that will make it so that at this step, your main.o file created by the assembler will NOT be discarded, but since we did not include one, that is exactly what will happen. It is also worth noting that since all we used in our command was gcc main.o without a -o flag, our executable will by default be saved to a.out. You are able to use the -o flag to rename your executable file as need be.

--

--