What does gcc main.c do?

Onsjannet
3 min readJun 10, 2020

--

The C language is one of the number 10 best programming languages it’s actually number 8 according to Github Data. it is an imperative language that have to be compiled with a compiler like gcc to create an executable file. gcc stands for GNU Compiler Collection it allows engineers to have a better control over the compilation process since it accepts options and file names as arguments.

now, what really happens when you type $gcc main.c?

when you type this command it automatically runs 4 steps that helps translate our program language to the machine language by changing our source code to an executable file it goes as follows: pre-processing, compilation proper, assembly and finally linking. the gcc command always runs the file in this order.

let’s try to explain the process of transforming our c program from a source code to a binary code or a machine language program.

let’s take an example a program called “ main.c”

1: Preprocessing

During preprocessing gcc interprets lines in files that have hashes. When we run : $ gcc main.c the program get processed by 1st removing all the comments.

first it will remove like the # and / and *. Look below for a visual aspect

#include <stdio.h>
/**
* main - Entry point
*
* Return: Always 0 (Success)
*/

then , it will include code from header and source file as a 2nd step

and finally it if there’s macros used in the program it will replace them with code.

the 1st step can be executed by running “$ gcc -E main.c” and that’s when the file enters the compilation stage with expanded macro language attached to it.

2 Compilation

During the 2nd step the gcc will play the role of a translator by translating the output of the 1st step “ Preprocessing” and change it to an assembly language.
Assembly code is the last stop when it comes to human readable form before becoming a machine language. the 2nd step can be executed by running “$ gcc -c main.c”

3 Assembly

in this step the assembler turn the output coming from the compiler and turn in into machine code also called binary. the output is being put in a file called main.o. this will became the final input of the final step Linking. To generate assembly code from the source file run “gcc -S main.c” and it will be put into a file called maine.o.

4 Linking

The last and final step the linker links together the code accepted from the main.o and the precompiled libraries imported with the #include preprocessor directive and merge them together into a code in the form of an executable file a.out.

let’s see how this looks :

$ gcc main.c
$ ls
$ main.c a.out

now let’s execute the code :

$ ./ouput

if the file was not specified using -o execute the a.out like below:

$ ./a.out

Finally you will get this output:

$ ./a.out
Hello World!
$

and that’s how you compile a .C file from start to finish.

--

--

No responses yet