Part 2 · 1 chapters · ~8 min

The Toolchain: Compiler, Linker, Loader, ELF and Mach-O

Preprocessing, compilation, assembly and linking step by step, object files and symbols, static and dynamic libraries, ELF and Mach-O layouts, the dynamic loader, position-independent code, build systems (make, CMake), and inspecting binaries.

3

Every stage, inspected

code
clang -E money.c | wc -l          # preprocessed source: thousands of lines from stdio.h
clang -S -O2 money.c              # money.s: assembly
clang -c -O2 money.c              # money.o: object file
nm money.o                        #   U _printf   (undefined: the linker must find it)
                                  #   T _main     (defined in text)
clang money.o -o money            # link against libc
otool -L money                    # macOS: /usr/lib/libSystem.B.dylib   (Linux: ldd money → libc.so.6)
readelf -h -l money               # Linux: ELF header, program headers (segments to map)

# a static library and a shared one
ar rcs libledger.a ledger.o                    # archive of objects, copied in at link time
clang -shared -fPIC -o libledger.so ledger.c   # shared: loaded at run time, shared between processes
code
# Makefile: rebuild only what changed
CFLAGS = -std=c17 -Wall -Wextra -O2
money: money.o ledger.o ; $(CC) $^ -o $@
%.o: %.c ledger.h       ; $(CC) $(CFLAGS) -c $< -o $@
FROM SOURCE TO RUNNING PROCESS
four tools and a loader
money.cpreprocessor#include, #define expandedcompilerC → assembly → objectlinkerobjects + libc → executableELF / Mach-Osections, symbols, segmentsloadermaps segments, runs main
swipe the figure sideways, or tap expand for full screen
1/5
preprocess
The preprocessor pastes headers and expands macros. clang -E shows the result: your 20-line file becomes thousands of lines.
text substitutionclang -E