The preprocessor is a step that runs before the compiler reads your C++ code. It works on the text of your source files. It copies in header files, replaces macro names with their definitions, and decides which parts of a file get compiled at all. Its instructions are lines that begin with #, and those lines are gone by the time the compiler parses the rest of the code.
Where the preprocessor fits in a build
Building a C++ program happens in stages, and the preprocessor goes first. Next, the compiler translates the preprocessed code into object files, and the linker combines those object files into a program. You don’t have to think about each stage every day, but knowing the order explains a lot of behavior. The compiler never sees a macro name, only the text it was replaced with. A header’s contents are also pasted in before any type checking happens.
Directives: the lines that start with
A preprocessor directive is a line whose first non-space character is #. Common directives include #include, #define, #undef, #if, #ifdef, #ifndef, #elif, #else, #endif and #error. Directives don’t end with a semicolon, and each one occupies its own line.
Including headers with #include
#include inserts the contents of another file at that spot, as if you had typed it there:
#include <iostream>
#include "geometry.h"
Angle brackets, as in <iostream>, tell the preprocessor to search the standard and system include paths. Quotes, as in "geometry.h", usually search the folder of the file that contains the directive first, then the same paths. The exact search rules depend on your compiler and build settings, so check its documentation if a header isn’t found.
Because the text is copied each time, including the same header twice repeats its contents. Headers handle that with guards, covered below.
Defining constants and macros with #define
#define creates a macro. The simplest form replaces one name with some text:
#define BUFFER_SIZE 256
char buffer[BUFFER_SIZE];
Before compilation, every BUFFER_SIZE becomes 256. A macro has no type and no scope. The preprocessor doesn’t know that the value is an integer, and it ignores blocks, classes and namespaces. Because macro names aren’t limited by scope, they can clash with names elsewhere in the program.
In modern C++, a constexpr variable is usually the better choice for a named constant:
constexpr int buffer_size = 256;
The compiler knows its type, and it follows normal scope rules.
Function-like macros and their pitfalls
A macro can also take arguments, so it looks like a function call:
#define SQUARE(x) ((x) * (x))
Before compilation, SQUARE(3) becomes ((3) * (3)). The extra parentheses matter. Without them, a version like #define SQUARE_BAD(x) x * x turns SQUARE_BAD(1 + 2) into 1 + 2 * 1 + 2, which evaluates to 5 instead of 9.
The larger problem is that arguments are pasted in as text. An argument with side effects, such as SQUARE(++n), can be evaluated more than once, and the result may be undefined. A regular function evaluates each argument once and checks the argument types. That’s why an inline or constexpr function is usually a safer choice for this kind of job.
Conditional compilation
Directives can also choose which code the compiler sees at all. This is useful for debug-only output or for code that differs between platforms:
#include <iostream>
int main() {
#ifdef DEBUG
std::cout << "Debug build\n";
#else
std::cout << "Release build\n";
#endif
}
#ifdef checks whether a macro is defined, and #ifndef checks whether it isn’t. #if evaluates a constant expression, and #elif adds another branch. With GCC or Clang, you can define a macro from the command line using -D:
g++ -DDEBUG main.cpp
With that flag, the first message is compiled in. Without it, the second message is.
Include guards and #pragma once
If the same header ends up included twice in the same source file, its declarations appear twice, and the compiler reports redefinition errors. Include guards prevent that. They look like this:
// point.h
#ifndef POINT_H
#define POINT_H
struct Point {
int x;
int y;
};
#endif
The first time the file is included, POINT_H isn’t defined, so the code is kept and the macro gets defined. Later inclusions skip the code, because the macro is already defined.
Most compilers also support #pragma once, which has a similar effect with less typing. The C++ standard doesn’t define it, so include guards are the more portable choice.
Predefined macros
Compilers define several macros for you. __FILE__ expands to the name of the current source file as a string, and __LINE__ expands to the current line number:
#include <iostream>
int main() {
std::cout << __FILE__ << ':' << __LINE__ << '\n';
}
C++ compilers also define __cplusplus, whose value identifies the language standard in use. For C++17 it is 201703L, so you can check for it with #if __cplusplus >= 201703L.
Seeing what the preprocessor produces
When a macro or include behaves in a way you didn’t expect, look at the preprocessed output. GCC and Clang stop after the preprocessing step and print the result when you pass -E:
g++ -E main.cpp
The output can run to thousands of lines, because it includes the full text of every header. Search for the part you care about, or redirect the output to a file and open it in an editor. MSVC has a similar option, /E.
Modern alternatives to common macros
Many jobs people once did with macros have safer C++ options:
- Constants: use
constexprvariables instead of#definevalues. - Small helpers: use an
inlineorconstexprfunction instead of a function-like macro. The compiler checks the types, and each argument is evaluated once. - Code for many types: use function templates, which the compiler generates for each type you actually use.
- Named sets of values: use an
enum classinstead of a list of macro constants.
Macros still have real uses. Include guards are one example, and conditional compilation for platform differences is another. Programmers often ask why not use macros in C++ at all. The main answer is that macros skip the compiler’s type checks and scope rules, so they’re best kept for jobs that really need the preprocessor.
Common mistakes
- Missing parentheses in a macro body, which can change how arguments combine.
- A semicolon after a
#definevalue. With#define N 10;, the lineint a[N];becomesint a[10;];, which is a syntax error. - Missing
#endif. Every#if,#ifdefor#ifndefneeds a matching#endif, or the compiler reports an error at the end of the file. - Name clashes. On Windows,
<windows.h>definesminandmaxmacros unlessNOMINMAXis defined before the include. Those macros can break calls such asstd::min. - Assuming an include loads a file only once.
#includecopies the text every time, so headers need guards.
Quick summary
The preprocessor runs first and works on text. It includes headers, defines macros and selects code using lines that begin with #. Use it for jobs that need it, such as include guards and conditional builds, and reach for constexpr values, inline functions and templates before a macro.