Getting the basics of linking right
We discussed the life cycle of a C++ program in Chapter 7, Compiling C++ Sources with CMake. It consists of five main stages – writing, compiling, linking, loading, and execution. After correctly compiling all the sources, we need to put them together into an executable. We said that object files produced in a compilation can't be executed by a processor directly. But why?
To answer this, let's understand that object files are a variant of the widely-used Executable and Linkable Format (ELF), common in Unix-like systems and many others. Systems like Windows or macOS have their own, different formats, but we’ll focus on ELF to explain the principle. Figure 8.1 shows how a compiler structures these files:
The compiler will prepare an object file for every unit of translation (for every .cpp
file). These files will be used to build an in-memory image of our program. Object files consist...