DEV Community

Cover image for C++ Compilation Pipeline.
Araiz Naqvi
Araiz Naqvi

Posted on

C++ Compilation Pipeline.

C++ is a high level language.

The main reasons why it's preferred taks specific:

  • OOP
  • Control over system resources and memory
  • Performance: Efficiency and Speed

Uses of C++:

  • System/Software dev
  • Game dev
  • Real Time Systems

.

Compilation Process


C++ compiler includes G++, clang++, etc.
The C++ execution pipeline works as follows:


STEP1: You write your source code

You create a file called main.cpp as follows:

#include <iostream>

int main() {
    int age = 25;
    std::cout << age << '\n';
    return 0;
}
Enter fullscreen mode Exit fullscreen mode


This src code is human readable instruction written in C++.
However, your CPU does not directly understand int, cout, etc, hence, this code needs to be translated into instructions suitable for your computer.
Here's where we enter the next stage.

STEP2: Preprocessing

Before the main translation, the preprocessor handles directives such as:

#include <iostream>
#define LIMIT 100
Enter fullscreen mode Exit fullscreen mode


This does not mean the complete implemenation of every library function is copied into your program, it makes note of all declarations and definitions needed for compilation and actual implementations will come from library files linked later.

A preprocessed source code is generate which enters the next stage.

STEP3: Compilation

The compiler will now take the preprocessed source and perform several jobs:

3.1 Syntax and Semantic Checking


It will checks whether the program follows all C++ rules.
If any error it throws a compilation error, otherwise, it moves to:

3.2 Optimization


Here, the compiler will simplify the code to make it faster/smaller without changing its main behaviour.

3.3 Code Generation


Your code is now converted into low level representation often Assembly Language,
So, you code goes from:

int add(int a, int b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode


to

mov eax, edi
add eax, esi
ret
Enter fullscreen mode Exit fullscreen mode

.

STEP4: Assembly

The Assembler converts assembly instructions into machine code bytes.
The output is an object file such as main.o in linux.

The object file will contain:

  • Machine Code instructions
  • Data used by the program
  • Info on symbols and references which are yet to be linked
  • Relocation info indicating where certain addresses will be adjusted.

.

STEP5: Linking

Imagine your program calls a function in another cpp file or uses functionality that is provided by a library, The compiler originally generated references without knowing the final addresses.

Now, the linker resolves these references and combines the required object files and libraries into the executable.
It connects and handles addresses and symbol references.

All this is now converted to an executable which is run by the CPU.

Top comments (0)