Linkers, Loaders & Object Formats

the ELF format

/ elf, like the storybook elf /

When a compiler turns your code into a finished program, it cannot just dump raw machine instructions into a file and hope the operating system knows what to do. The bytes need a container: a known layout that says where the code is, where the initialized data is, what symbols the program defines or needs, and how to fix up addresses. On Linux and most Unix-like systems, that container format is called ELF. The same format is used for object files (the .o files the compiler emits), for finished executables, and for shared libraries (.so files).

An ELF file always starts with a fixed-size ELF header that begins with the four magic bytes 0x7f 'E' 'L' 'F' (often written 0x7f 0x45 0x4c 0x46). From that header, two tables can be reached. The section header table describes the file as a set of named sections (.text for code, .data for initialized data, .symtab for the symbol table, and so on) — this is the view the linker cares about. The program header table describes the file as a set of segments, which tell the loader which ranges of the file to map into memory and with what permissions. One physical file, two ways of slicing it: sections for linking, segments for loading.

ELF matters because it is the single common language that the compiler, the linker, the dynamic linker, and the kernel all speak about a program. You can inspect any ELF file with readelf or objdump and see exactly what is inside. A common misconception is that an ELF executable contains a single flat blob of code — in reality it is a structured archive whose pieces are laid out, named, and cross-referenced, which is precisely what makes separate compilation and dynamic linking possible.

$ readelf -h ./a.out Magic: 7f 45 4c 46 02 01 01 00 ... Class: ELF64 Type: DYN (Position-Independent Executable) Entry point address: 0x1060

The first bytes 7f 45 4c 46 are the ELF magic number; the header then states the class (64-bit), the file type, and where execution begins.

ELF is the Linux/Unix format; Windows uses PE/COFF and macOS uses Mach-O. The bytes are not interchangeable, but the underlying ideas — header, sections, symbols, relocations — are the same everywhere.

Also called
Executable and Linkable FormatELF 檔可執行與可連結格式