The Basics of Compilation
Let's learn the basics of compilation and its components.
Compilation can be roughly described as a process of translating instructions written in a higher-level programming language to a low-level machine code. This allows us to create our applications using abstract concepts such as classes and objects and not bother with the tedious details of processor-specific assembly languages. We don't need to work directly with CPU registers, think about short or long jumps, and manage stack frames. Compiled languages are more expressive, readable, and secure, and foster more maintainable code (but are still as performant as possible).
In C++, we rely on static compilation—an entire program has to be translated into native code before it is executed. This is an alternative approach to languages such as Java or Python, which compile a program on the fly with a special, separate interpreter every time a user runs it. There are certain advantages to each method. The policy of C++ is to provide as many high-level tools as possible while still being able to deliver native performance in a complete, self-contained application for almost every architecture out there.
It takes a few steps to create and run a C++ program:
Design our application and carefully write the source code.
Compile individual
.cpp
implementation files (called translation units) to object files.Link object files together in a single executable and add all other dependencies—dynamic and static libraries.
To run the program, the OS will use a tool called loader to map its machine code and all required dynamic libraries to the virtual memory. The loader then reads the headers to check where the program starts and hands over control to the code.
C++ runtime kicks in; a special
_start
function is executed to collect the command-line arguments and environment variables. It starts threading, initializes static symbols, and registers cleanup callbacks. Only then will it callmain()
, which is filled with code by the programmer.
As you can see, quite a lot of work happens behind the scenes. This is about the second step in the preceding list. By taking the whole picture into consideration, we can understand better where some of the possible issues come from. After all, ...