Professional Practice: Headers, Libraries, Linker Errors and CMake
Split a program into headers and source files, build a static library with ar, see the real undefined reference linker error, and build the same project with CMake, with every command run for real.
In this lesson you will
- Split code into headers and sources
- Compile and link separately
- Build a static library
- Build with CMake
About 28 minutes
One file is not a project
Elena’s program has grown to a thousand lines in one file, and every change recompiles all of it. Real projects split code into headers, which declare what exists, and source files, which define it. A header (.h or .hpp) contains declarations that many files need, protected by an include guard or #pragma once so that it is not processed twice. A source file (.cpp) contains the definitions and is compiled separately into an object file. The linker then joins the object files, and fails with an “undefined reference” error if a function was declared and used but never defined anywhere.
Several object files can be packed into a static library with the ar tool, and linked into programs with -L for the folder and -l for the name. A build system keeps track of which files changed and rebuilds only those. CMake is a widely used build description that generates the actual build files for make or other tools. The program below does all of this for a small two-file library, in a temporary folder, and shows the real output of every step.
| File | Role |
|---|---|
| pricing.h | Declares the functions, with an include guard |
| pricing.cpp | Defines them |
| main.cpp | Uses them |
| libpricing.a | A static library made with ar |
| CMakeLists.txt | Describes the build to CMake |
#pragma once
int total_cents(int cups, int unit_cents = 320);
const char* version();
#include "pricing.h"
int total_cents(int cups, int unit_cents) { return cups * unit_cents; }
const char* version() { return "pricing 1.0"; }
#include <iostream>
#include "pricing.h"
int main() { std::cout << version() << ": 3 cups cost " << total_cents(3) << "\n"; }
$ g++ -std=c++20 -Wall -Wextra -c pricing.cpp -o pricing.o
$ g++ -std=c++20 -Wall -Wextra -c main.cpp -o main.o
$ ar rcs libpricing.a pricing.o
$ g++ main.o -L. -lpricing -o app
$ ./app
pricing 1.0: 3 cups cost 960
$ g++ main.o -o broken (forgot the library)
undefined reference to `version()'
$ cmake -S . -B build
$ cmake --build build
$ ./build/cmapp
pricing 1.0: 3 cups cost 960
Each step ran for real. The two source files were compiled separately into pricing.o and main.o, and ar packed pricing.o into the static library libpricing.a, 1,738 bytes, against an object file of 1,568 bytes. Linking main.o with the library gave a working program that printed “pricing 1.0: 3 cups cost 960”, which comes from code compiled in another file. The call total_cents(3) used the default argument from the header, 320, so 3 cups cost 960.
Forgetting the library produced the classic linker error: “undefined reference to `version()'”. The compiler was satisfied, since main.cpp only needs the declaration from the header, and it is the linker that finds that no object file defines the function. Reading linker errors gets easy once you know their meaning: a declared name was used and never defined, so a source file or library is missing from the link line. The CMake build produced the same program, with its own folder for build files, and printed the same text. It rebuilds only what changed, and it works the same on Linux, macOS and Windows with a suitable compiler.
Check by hand: 3 x 320 = 960. A header with a function body defined in it, without the keyword inline, would give a different linker error, “multiple definition”, when two source files include it, which is why definitions belong in .cpp files, apart from templates and inline functions.
Why separate compilation helps
Splitting a project has a practical payoff beyond tidiness. When you change one source file, only that file and the final link need to run again, so a large project rebuilds in seconds instead of minutes. Headers also define the boundary of a component: other code sees only the declarations, so you can change the implementation freely as long as the declarations stay the same. Keep headers small and free of unnecessary includes, because every change to a header recompiles every file that includes it, directly or through other headers, and that is the main reason that big C++ projects have long build times.
Non-inline function definitions in a header are compiled into every file that includes it, and the linker then reports multiple definitions. Declare in the header, define in the source file.
Guard every header, compile with -Wall -Wextra from the start, and let CMake or another build tool do the bookkeeping instead of typing commands.
Every program in this lesson was compiled with GCC 13 using -std=c++20 -Wall -Wextra and run while the course was written. C++ has a new standard every three years and compilers differ in what they support, so check your compiler’s documentation and cppreference.com for the current state. The build steps used GCC, ar and CMake 3 on Linux.
Practice
Add a second function to the library and a header guard, rebuild and check which files were recompiled. Add a test executable in CMake with add_test and run ctest. Turn on -fsanitize=address for the whole project with a CMake option.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does a header usually contain?
- All the definitions
- The compiled code
- Only comments
- Declarations
Definitions go in .cpp files.
What does the linker do?
- Compiles each file
- Preprocesses includes
- Joins object files and libraries
- Formats code
And reports undefined references.
What does “undefined reference” mean?
- A syntax error
- A missing semicolon
- A name was used but never defined in any linked file
- A slow loop
Add the missing source or library.
What does ar rcs make?
- An executable
- A static library
- A header
- A test
libpricing.a.
Why use CMake?
- It compiles faster by itself
- It describes the build and rebuilds what changed
- It replaces the compiler
- It formats code
It generates make files.
Summary
- Headers declare, sources define, and the linker joins object files.
- Static libraries are made with ar and linked with -l.
- Undefined reference means a missing definition at link time.
- CMake describes and automates the build.
Questions
What is the difference between a static and a shared library?
A static library is copied into the executable at link time. A shared library is loaded when the program runs, so several programs can share one copy.
What are C++20 modules?
A newer alternative to headers that compile faster and avoid include problems. Tool support is still maturing, so check your compiler and build system.
Which build system should I use?
CMake is the most widely used, and others such as Meson and Bazel exist. Use whatever your project or team uses.
