The Preprocessor and Compilation (C++ Core #7)
The preprocessor runs before the compiler and does one thing: text substitution. The linker runs after compilation and does another: matching names to addresses. Most “it compiles but does not build” questions are about which of the two failed, and most macro questions are about the fact that the preprocessor has no idea what a type or a scope is.
#include
#include pastes a file into the current one. Angle brackets search the system and
compiler include paths; quotes search the current directory first, then the same
paths.
#include <vector> // standard library
#include "myheader.h" // local
Includes are transitive: if a.h includes b.h, every file that includes a.h
also gets b.h. That is convenient and also why one missing include can hide
behind another for months. The discipline is “include what you use”: if a file
uses std::vector, it includes <vector>, even if some other header already
pulled it in.
Headers should contain declarations, not definitions, except for inline
functions, templates, and constexpr functions. A header included by twenty
translation units is compiled twenty times, which is why heavy includes slow
builds. Forward declarations (class Foo;) reduce that when only a pointer or
reference is needed.
#include <vector> inside a header make every file thatincludes that header slower to compile?
ASolution
The preprocessor copies the whole vector header into each translation unit, so the compiler parses it again each time. Includes are textual, not cached.
#define
#define creates a macro: a name replaced by tokens before compilation.
#define MAX_SIZE 100
#define PI 3.14159
Macros have no type, no scope, and no debugger support. They are replaced everywhere, including inside other identifiers’ neighbours:
#define MAX 100
int MAX_VALUE = 5; // becomes int 100_VALUE = 5; compile error
Use constexpr instead:
constexpr int MAX_SIZE = 100;
constexpr double PI = 3.14159265358979323846;
constexpr is typed, scoped, visible to the debugger, and evaluated at compile
time. The only things that still need the preprocessor are conditional
compilation and include guards.
#define MAX 100 break code that uses a variable namedMAX_SIZE?
ASolution
Macro replacement is token-based. MAX_SIZE starts with the token MAX, and
the preprocessor substitutes it, producing 100_SIZE, which is not a valid
identifier.
Function-like macros
#define SQUARE(x) x * x
#define MAX(a, b) ((a) > (b) ? (a) : (b))
SQUARE(2 + 3) expands to 2 + 3 * 2 + 3, which is 11. Parenthesize every
parameter and the whole body:
#define SQUARE(x) ((x) * (x))
Parentheses do not fix multiple evaluation:
int i = 3;
int j = SQUARE(i++); // ((i++) * (i++)), UB
The preprocessor substitutes text, so i++ appears twice. An inline function or
a template does not have that problem:
template <class T>
constexpr T square(T x) { return x * x; } // evaluates the argument once
Multi-statement macros need a do { ... } while (0) wrapper so they behave like a
single statement:
#define SWAP(a, b) do { auto t = (a); (a) = (b); (b) = t; } while (0)
if (x) SWAP(a, b);
else something();
Without the wrapper, the trailing ; after the macro body breaks the if/else
pairing.
do { ... } while (0) preferred over { ... } for amulti-statement macro?
ASolution
A bare block followed by a semicolon is a statement, so if (x) MACRO; else ...
works, but the block does not absorb the semicolon and the macro cannot be used
as an expression. do { } while (0) is a single statement that ends with a
semicolon and works in every context.
Macro expansion
The preprocessor expands macros recursively until no more replacements apply, but it will not expand a macro inside its own expansion (to prevent infinite loops).
#define A B
#define B 42
A // becomes 42
#define SELF SELF
SELF // stays SELF
Two operators do useful work at expansion time:
#define STR(x) #x
STR(hello) // "hello"
#define CAT(a, b) a##b
CAT(foo, bar) // foobar
# stringizes the argument without expanding it first; ## pastes tokens. Both
are used in assertion and logging macros (__FILE__, __LINE__).
A common trap is that # prevents expansion:
#define NAME "world"
#define STR(x) #x
STR(NAME) // "NAME", not "world"
Use an extra indirection level if you want the expansion:
#define XSTR(x) STR(x)
XSTR(NAME) // "world"
CAT(1, 2) produce, and is it a valid expression?ASolution
The token 12. Pasting digits creates a new numeric literal, which is valid.
Pasting arbitrary tokens can create invalid tokens, which is UB.
Conditional compilation
#define DEBUG 1
#if DEBUG
std::cout << "debug\n";
#endif
#ifdef _WIN32
// Windows-only
#elif defined(__linux__)
// Linux-only
#else
// other
#endif
#if 0
// disabled code
#endif
#if evaluates constant integer expressions with defined(X), arithmetic, and
comparisons. #ifdef X is #if defined(X). The preprocessor cannot see constexpr
values, types, or sizeof, so #if sizeof(int) == 4 is invalid.
#if 0 is the old way to comment out code that contains comments; it is also the
only reliable way to disable a block without nesting comment markers.
#if use a constexpr variable?ASolution
The preprocessor runs before the compiler. It only knows macros and literal tokens, so a C++ variable does not exist yet.
Header guards and #pragma once
A header included twice in the same translation unit defines everything twice. Guards make the second inclusion empty.
// util.h
#ifndef UTIL_H
#define UTIL_H
int add(int, int);
#endif
#pragma once does the same thing with less typing, and it is supported by every
major compiler. It is not in the standard, but it is universally available in
practice.
Guards still matter for portability and for the rare case where the same file is
reachable through two paths (symlinks, network mounts); #pragma once uses file
identity, which can differ.
Neither stops the header from being included in different translation units — that is expected, since each TU is compiled separately.
ASolution
No. They prevent a header from being processed twice in one translation unit. Definitions still appear in every TU that includes the header, so a non-inline function in a header still gives a multiple-definition link error.
Multiple definition errors and the ODR
The One Definition Rule says:
- A function or variable may be defined only once in a program.
- A class, enum, template, or inline function may be defined in multiple translation units, but the definitions must be identical and the linker picks one.
// util.h
int add(int a, int b) { return a + b; } // WRONG: definition in a header
// a.cpp, b.cpp both include util.h
// link: multiple definition of 'add(int, int)'
Fixes: mark it inline, move the body to one .cpp, or make it a template.
inline int add(int a, int b) { return a + b; } // ok, merged by the linker
Global variables have the same rule. In C, int x; at file scope is a tentative
definition and multiple TUs merge; in C++, it is a definition, so two TUs with
int x; give a multiple-definition error. Use extern int x; in the header and
one definition in a .cpp, or inline int x = 0; in C++17.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.2cm, minimum height=0.6cm, font=\scriptsize, align=center},
a/.style={->, thick}]
\node[b, fill=blue!10] (a) at (0,1.4) {a.cpp};
\node[b, fill=blue!10] (b) at (0,0) {b.cpp};
\node[b, fill=orange!15] (h) at (3.0,0.7) {util.h\\definition};
\node[b, fill=green!18] (l) at (6.0,0.7) {linker};
\draw[a] (a) -- (h); \draw[a] (b) -- (h);
\draw[a] (h) -- node[above, font=\scriptsize] {two copies} (l);
\node[font=\scriptsize, anchor=north, text=red!70!black] at (6.0,0.15) {multiple definition};
\end{tikzpicture}
.cpp files define int counter = 0; at global scope. What errordo you get, and how do you fix it in C++17?
ASolution
A multiple-definition link error. Put inline int counter = 0; in the header,
or extern int counter; in the header and one definition in a .cpp.
Compilation errors versus linker errors
Knowing which stage failed tells you where to look.
| Message | Stage | Typical cause |
|---|---|---|
'x' was not declared in this scope |
compile | missing declaration or include |
expected ';' before ... |
compile | syntax error |
invalid use of incomplete type |
compile | forward declaration only, needs the full definition |
no matching function for call |
compile | wrong arguments, missing overload |
undefined reference to 'foo' |
link | declared and used, never defined |
multiple definition of 'foo' |
link | definition in a header, or duplicated in two .cpps |
cannot find -lfoo |
link | library not on the link line or wrong path |
undefined symbol: _Z3fooi |
link/load | mangled name mismatch, often extern "C" missing |
An undefined reference is not a missing include. The compiler saw the
declaration; the linker could not find the body. That usually means a .cpp was
not compiled, a library was not linked, or the signature does not match.
// header
void f(int);
// definition
void f(double) { } // different function: overload, not the declared one
// link: undefined reference to f(int)
Name mangling encodes the signature in the symbol, which is why C and C++ need
extern "C" to link together:
extern "C" void c_function(int); // no name mangling
undefinedreference. Is the header wrong?
ASolution
Usually not. The declaration is enough to compile. The definition is missing at link time: not compiled, not linked, or a different signature.
Static and dynamic linking
Static linking copies the library code into the executable at link time
(.a archives on Unix, .lib on Windows). The result is self-contained and
larger.
Dynamic linking records a dependency on a shared library (.so, .dll) that
is loaded at program start or first use. The executable is smaller, and a patched
library can fix all programs without relinking.
g++ main.cpp -o app # dynamic by default
g++ main.cpp -o app -static # static, if static libs are installed
g++ -shared -fPIC util.cpp -o libutil.so
g++ main.cpp -L. -lutil -o app
ldd app # list the shared libraries it needs
Shared libraries must be position-independent (-fPIC) because they are mapped
at a runtime address. Static libraries do not need it.
Dynamic linking introduces ABI concerns: the binary interface (name mangling, class layout, calling convention, standard library ABI) must match between the executable and the library. Two different compilers on the same platform may not be ABI-compatible.
-fPIC?ASolution
It is loaded at an address chosen at runtime, so its code cannot use absolute addresses. Position-independent code uses relative addressing and relocations so it can be mapped anywhere.
inline, inline variables, and LTO
inline on a function is a request to the compiler, and more importantly a
linker promise: multiple identical definitions across TUs are allowed and merged.
Since C++17, inline also applies to variables:
inline int counter = 0; // one entity across all TUs
inline constexpr double pi = 3.14159265358979323846;
inline does not guarantee inlining. The compiler decides, and modern compilers
inline small functions without the keyword. [[gnu::always_inline]] and
__forceinline are non-standard ways to insist.
Without inline, a function defined in a header appears in every TU that includes
it. The linker rejects the duplicates unless one of them is inline.
Link-Time Optimization (-flto) lets the compiler optimize across
translation-unit boundaries at link time: inlining across files, dead code
elimination, constant propagation. The cost is longer link times and a
requirement that all objects are built with compatible LTO settings.
inline force the compiler to inline a function?ASolution
No. It is a hint plus an ODR permission. The optimizer decides based on size,
cost, and flags. inline mainly prevents multiple-definition errors.
Bugs and edge cases
- Macro name collisions.
#define min(a,b)breaksstd::min,<algorithm>, and any identifier starting withmin. - Missing parentheses in macros.
#define NEG(x) -xused asNEG(a + b). - Multiple evaluation.
SQUARE(i++),MAX(f(), g()). - Headers with definitions. Multiple-definition link errors.
- Include cycles. Two headers including each other; guards stop recursion but the type may be incomplete at the point of use.
- Conditional compilation skew. Different TUs see different macro values, which violates the ODR silently.
assertandNDEBUG.assert(expr)disappears whenNDEBUGis defined (release builds), so never put side effects inside it.- String comparison with macros.
#define NAME "x"thenif (name == NAME)compares pointers ifnameischar*. #pragma oncewith generated files. Regenerating a header with the same path can confuse build systems that cache file identity.
#define min(a, b) ((a) < (b) ? (a) : (b)) breaks code usingstd::min. Why?
ASolution
The preprocessor replaces the token min everywhere, including after std::,
producing std::((a) < (b) ? (a) : (b)), which is not valid. Macros ignore
namespaces and scopes.
Next: Structs, Unions, and Memory Layout (C++ Core #8) — padding, alignment, and sizeof calculations.