Compiling C files with gcc

Stiven Gonzalez
2 min readFeb 4, 2021

What is C Programming Language?

C is a general-purpose programming language that is extremely popular, simple, and flexible to use. It is a structured programming language that is machine-independent and extensively used to write various applications, Operating Systems like Windows, and many other complex programs like Oracle database, Git, Python interpreter, and more.

Compiling C files with gcc, step by step

Compilation

Compilation is the translation of source code (the code we write) into object code (sequence of statements in machine language) by a compiler.

The compilation process has four different steps:

  • The preprocessing
  • The compiling
  • The assembling
  • The linking

The compiler we will be using as an example is gcc which stands for GNU Compiler Collection.

1. The preprocessor

During compilation of a C program the compilation is started off with preprocessing the directives (e.g., #include and #define).

The preprocessor has several roles:

  • it gets rid of all the comments in the source file(s)
  • it includes the code of the header file(s), which is a file with extension .h which contains C function declarations and macro definitions
  • it replaces all of the macros (fragments of code which have been given a name) by their values

2. The compiler

The compiler will take the preprocessed file and generate IR code (Intermediate Representation), so this will produce a “.s” file. That being said, other compilers might produce assembly code at this step of compilation.

3. The assembler

Assembly is the third step of compilation. The assembler will convert the assembly code into pure binary code or machine code (zeros and ones). This code is also known as object code.

4. The linker

The linker creates the final executable, in binary, and can play two roles:

  • linking all the source files together, that is all the other object codes in the project.
  • linking function calls with their definitions. The linker knows where to look for the function definitions in the static libraries or dynamic libraries.

By default, after this fourth and last step, that is when you type the whole “gcc main.c” command without any options, the compiler will create an executable program called a.out, that we can run by typing “./a.out” in the command line.

--

--