...

/

Getting the Basics of Linking Right

Getting the Basics of Linking Right

Let's learn about how and when to link files in CMake.

The life cycle of a C++ program 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.

Structure of an object file

Object files produced in a compilation can't be executed by a processor directly. But why? To answer this, let's take a look at how a compiler structures an object file in the popular ELF format (used by Unix-like systems and many others):

Press + to interact
The structure of an object file
The structure of an object file

The compiler will prepare an object file for every translation unit (for every .cpp file). These files will be used to build an in-memory image of our program. Object files contain the following elements:

  • An ELF header identifying the target operating system, ELF file type, target instruction set architecture, and information on the position and size of two header tables found in ELF files: the program headers table (not present in object files) and the section headers table.

  • Sections containing information grouped by type (described next).

  • A section headers table containing information ...