What happens when you type gcc main.c ?

Stages of gcc compilation

Source files, such as main.c, contain text commands that are yet to be compiled and assembled into an executable file. These commands are written in different programming languages such as C. The GNU Compile Collection (GCC) is a compiler system produced by the GNU Project and the command gcc is used to compile a source code into an executable file.

The command below results in a new file named a.out which is the executable file for main.c.

gcc main.c

Compilation steps:

The compilation process is comprised of four different steps: preprocessor, compiler, assembler, and linker.

The initial step, preprocessor, takes the source code and makes some changes to it. It gets rid of the comments, as they are not part of the commands needed to run the program. It also includes codes from the header files such as <stdio.h> and finally, replaces macro names by their values or definitions.

gcc -E main.c

To stop the compiler after the preprocessor step, the option -E is passed to the gcccommand.

The next step, compiler, takes the preprocessed code and converts it into assembly code. The assembly code is still in human language and not machine language.

gcc -S main.c

The stop the compiler after the compiler step, the opton -S is passed to the gcccommand. The above command creates a file called main.s which contains the assembly code for the main.c file.

The third step, assembler, takes the file main.s with the assembly code from the previous step and compiles or assembles into object code. The object code now is in machine language or the binary.

gcc -c main.c

To stop the compiler after the assembler step, the option -c is passed to the gcccommand. Running the command above produces a new file called main.o containing the object code for the main.c file.

The final step, linker, as its name implies links all the object codes from different sources and puts them together. Any library files that were included in the source files are also merged to produce the final executable file.

gcc -o main main.c

Running the command above will create an executable file called main. By default, if the option -ois not specified with a name, a new file a.out will be created. The newly created file is the executable file for the source file.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.