Lesson 2 / 25
Compiling, Linking and Warnings
Compile and link programs with g++ or clang++ and use warnings and standards flags.
Translation units and the build pipeline
Building a C++ program has several stages. The preprocessor handles #include (pasting header contents in) and macros. The compiler translates each source file (.cpp), together with the headers it includes, called a translation unit, into an object file (.o or .obj) of machine code. The linker combines object files and libraries into an executable, resolving references to functions defined in other files. Common compilers are GCC (g++), Clang (clang++) and MSVC (cl on Windows). Always choose a language standard (-std=c++20 or -std=c++23) and enable warnings: -Wall -Wextra -Wpedantic catch many bugs, and -Werror makes warnings fail the build. Use -O2 for optimised builds and -g for debug information. For anything beyond a few files, a build system such as CMake (covered later) generates the compiler commands for you.
Compiling one and several files
Separate compilation means only changed files are recompiled.
# one file, C++20, warnings on, debug info
g++ -std=c++20 -Wall -Wextra -Wpedantic -g hello.cpp -o hello
./hello
# several files: compile each to an object file, then link
g++ -std=c++20 -Wall -Wextra -c geometry.cpp -o geometry.o
g++ -std=c++20 -Wall -Wextra -c main.cpp -o main.o
g++ geometry.o main.o -o app
# optimised release build
clang++ -std=c++23 -O2 -DNDEBUG main.cpp geometry.cpp -o appChapters, printing and binding
Each source file is a chapter typeset separately (compiling). Binding the chapters into one book, with page references between chapters resolved, is linking. A broken cross-reference shows up only at binding time, just like an "undefined reference" linker error.
Quick check: What does the linker do?
- Expands #include directives
- Checks syntax of each source file
- Runs the program
- Combines object files and libraries into an executable, resolving references between them
Answer
Combines object files and libraries into an executable, resolving references between them — The linker resolves symbols across object files and libraries to produce the final binary.