Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 171 ยท Functions

The Preprocessor and Macros

Learn the C++ preprocessor - #define macros and their pitfalls, # and ##, conditional compilation, predefined macros, #warning, __has_include and feature-test macros.

Before the C++ compiler sees a single declaration, another program has already rewritten your source file: the preprocessor. It handles every line that starts with #. #include pastes in a header, #define creates a macro that is replaced by text, and #if keeps or deletes whole blocks of code. The preprocessor knows nothing about types, scopes or namespaces; it works on tokens, the words and symbols of your program, and its output is what the compiler actually compiles.

C++ inherited the preprocessor from C, and modern C++ has spent decades making most uses of it unnecessary: constexpr replaces constant macros, templates and inline functions replace function-like macros, if constexpr replaces much conditional compilation, std::source_location replaces __FILE__ and __LINE__, and modules aim to replace #include. But you still need it for headers, platform and compiler differences, feature detection and a few tricks nothing else can do, and you'll read macro-heavy code in every large project. This lesson covers all of it, including the pitfalls that make experienced programmers avoid macros whenever they can.

You should have read Header Files and Multiple Source Files, which explains #include, include guards and translation units.

What the preprocessor does

Compiling a .cpp file happens in phases. The preprocessor runs first: it removes comments, joins lines that end with a backslash, executes the directives, and expands macros. The result, one long stream of tokens called a translation unit, goes to the compiler proper. You can look at it yourself:

Terminal
g++ -E main.cpp -o main.ii      # GCC/Clang: preprocess only
cl /P main.cpp                  # MSVC: writes main.i

A ten-line program that includes <iostream> turns into tens of thousands of lines, because every included header is pasted in. Reading -E output is the most reliable way to debug a confusing macro.

A directive is a line whose first non-space character is #: #include, #define, #undef, #if, #ifdef, #ifndef, #elif, #else, #endif, #error, #warning, #pragma and #line. A directive ends at the end of the line, so a long macro continues onto the next line with \.

Object-like macros

#define NAME replacement makes every later occurrence of the token NAME turn into the replacement text. These are object-like macros:

C++
#define MAX_PLAYERS 8
#define GREETING "Welcome!"

In C this is how constants are written. In C++ it's almost always the wrong choice, because a macro ignores the rules every other name follows. It has no type, it can't be put in a namespace or a class, and it's replaced everywhere after its definition, including inside unrelated code:

C++ Macros ignore scopes and namespaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Neither the namespace nor the function body limits the macros: the preprocessor runs before scopes exist. The commented-out line shows a typical confusing error, because game::MAX_PLAYERS is turned into game::8 before the compiler sees it. A constexpr variable has none of these problems: it has a type, it obeys scopes, the debugger knows its name, and it can be used in templates and static_assert. Use constexpr (or inline constexpr in a header) for every constant; see Constants.

Macro names collide with everything, which is why they're conventionally written in ALL_CAPS and never used for anything else. The most famous accident is <windows.h>, which defines macros called min and max, so std::max(a, b) stops compiling on Windows unless you define NOMINMAX first or write (std::max)(a, b).

Function-like macros and their pitfalls

A macro with a parameter list (no space before the () is a function-like macro. Its arguments are pasted into the replacement as tokens, without being evaluated first:

C++ Function-like macros versus a constexpr function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

SQUARE_BAD(2 + 3) expands to 2 + 3 * 2 + 3, which is 11, not 25. Parentheses around each parameter and the whole body fix that, but nothing fixes the second problem: an argument is evaluated once per appearance in the body. SQUARE(next_reading()) calls the function twice and multiplies two different readings (3 ร— 4 = 12), when you wanted one reading squared. With SQUARE(n++) it's even worse: n is modified twice without sequencing, which is undefined behavior (GCC warns operation on 'n' may be undefined). The function template evaluates its argument exactly once (3 ร— 3 = 9), is type-checked, and is just as fast because it's inlined.

The rule for C++ is simple: if a function can do the job, write a function (inline, constexpr or a template; see Inline Functions and Function Templates). Multi-statement macros, when you must write them, are wrapped in do { ... } while (0) so they behave like one statement after an if.

Stringizing (#), token pasting (##) and variadic macros

Macros can do two things no function can. In a function-like macro, #param turns the argument into a string literal of its source text, and a ## b pastes two tokens into one. ... with __VA_ARGS__ accepts any number of arguments, and C++20's __VA_OPT__(text) inserts text only when there are extra arguments:

C++ Stringizing, pasting and a variadic macro

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

SHOW(6 * 7) prints 6 * 7 = 42: the text and the value of the same expression, something only a macro can produce. That's why assert and test frameworks such as GoogleTest and Catch2 are macros. #level makes "INFO", and adjacent string literals are joined, so the format string becomes "[INFO] " "server started". Without __VA_OPT__, LOG(INFO, "server started") would expand to a call ending in a stray comma.

To stringize the value of another macro instead of its name, you need two levels, because # doesn't expand its argument:

C++
#define STR(x) #x
#define XSTR(x) STR(x)
#define VERSION 3
STR(VERSION)    // "VERSION"
XSTR(VERSION)   // "3"

Conditional compilation

#if, #elif, #else and #endif keep or delete code before compilation. The condition is an integer constant expression built from literals, macros and the defined(NAME) operator; any identifier that isn't a macro counts as 0. #ifdef NAME and #ifndef NAME are shorthands, and C++23 adds #elifdef and #elifndef. Typical uses:

  • Platforms and compilers: _WIN32 (Windows, also 64-bit), __linux__, __APPLE__; _MSC_VER (MSVC), __clang__, __GNUC__ (GCC, but Clang defines it too, so test __clang__ first).
  • Build configurations: macros passed on the command line with -DNAME or -DNAME=value (/D in MSVC), and NDEBUG, which release builds define to turn off assert (see Assertions and Debugging).
  • Temporarily disabling code: #if 0 ... #endif nests correctly, unlike /* */ comments.
C++ Choosing code by platform and build settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The code in the branches that aren't taken is never compiled at all, so it can even contain Windows-only calls that wouldn't compile on Linux. That's the difference from if constexpr, which also discards a branch but only inside templates, and still requires the code to be valid C++ that parses. Prefer if constexpr (see constexpr and Compile-Time Programming) for decisions about types and constants, and keep #if for platform and build switches. Keep those switches at the edges of your program, in one small file per platform, rather than scattered through every function.

Predefined macros and source locations

Every compiler defines some macros on its own. The most useful standard ones:

Macro Value
__cplusplus The language version: 201103L (C++11), 201402L, 201703L, 202002L (C++20), 202302L (C++23)
__FILE__ The current source file name, as a string literal
__LINE__ The current line number, as an integer
__DATE__, __TIME__ When the file was compiled (bad for reproducible builds)
__STDC_HOSTED__ 1 when the full standard library is available

__func__ looks like one of them but isn't a macro: it's a variable the compiler defines inside every function, holding the function's name. And C++20's std::source_location (from <source_location>) gives you all of this as an ordinary object, which can be a default function argument. That one feature removes the main reason logging and assertion helpers were written as macros:

C++ Predefined macros and std::source_location

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

__cplusplus is 202302 here because our compiler runs in C++23 mode. (MSVC reports 199711L for historical reasons unless you compile with /Zc:__cplusplus.) The default argument std::source_location::current() is evaluated at the call site, so log_here reports the line that called it, with the full function signature, without any macro.

#error, #warning and #pragma

#error message stops compilation with your message, which is the standard way to reject unsupported configurations. #warning message prints a warning and continues; it was a compiler extension for decades and became standard in C++23:

C++ Compile-time messages with #warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The program runs, and the compiler output above it shows warning: #warning "The legacy parser is deprecated and will be removed in version 3" [-Wcpp]. Change the condition to CHAR_BIT == 8 and the build fails with the #error message instead. For conditions that involve types or constants, static_assert is the better tool, because it runs after the compiler knows about types.

#pragma passes implementation-specific instructions to the compiler; compilers ignore pragmas they don't recognize. Common ones:

C++
#pragma once                                      // include guard (see Header Files)
#pragma GCC diagnostic push                       // GCC/Clang: change warnings locally
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// ... code that uses a deprecated API ...
#pragma GCC diagnostic pop
#pragma pack(push, 1)                             // structure packing (MSVC, GCC, Clang)

#pragma once is supported by every major compiler and is simpler than an include guard, while guards are standard and work even in odd setups where the same file is reachable through two paths. Both are fine; Header Files compares them.

Detecting features: __has_include and feature-test macros

Compilers and standard libraries add C++ features at different speeds, so portable code often asks "is this available?" instead of checking version numbers. Two tools answer that:

  • __has_include(<header>) (C++17) is true when the header can be included.
  • Feature-test macros (C++20 standardized them) describe individual features. Library features like __cpp_lib_print are defined by <version> (and by the header that provides them); language features like __cpp_concepts are always defined by the compiler. The value is the year and month the feature was standardized, such as 202207L. __has_cpp_attribute(name) does the same for attributes.
C++ Checking for features before using them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Our GCC 15 library doesn't ship <mdspan> yet, and C++26 reflection isn't in this compiler, so the program takes the fallback branches for those. A library that wants std::print when available and printf otherwise, or std::expected with a home-made replacement for older compilers, uses exactly these checks. Test the specific macro you need rather than __cplusplus: a compiler can claim C++23 while still missing some C++23 library features.

Modern replacements for macros

Most macros in old C++ code have a better modern equivalent. When you write new code, use the right column:

Old macro technique Modern C++
#define SIZE 64 constexpr int size = 64; (inline constexpr in headers)
Function-like macros such as SQUARE(x) constexpr/inline functions and templates
Macros that work for any type Templates, overloading, concepts
#if on types or constants if constexpr, static_assert, requires
__FILE__/__LINE__ in logging macros std::source_location as a default argument
Include guards and #include Modules: import std; (C++23)
Enum-to-string macro tricks Still macros (X-macros) today; C++26 reflection will replace them

What remains for the preprocessor is genuinely preprocessing: #include (until modules take over), platform and compiler switches, feature detection, and the few macros that need the source text of their arguments (#), the caller's tokens, or code generation (##). Keep those macros short, ALL_CAPS, fully parenthesized, and #undef the ones that are only needed locally.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given #define TWICE(x) x + x, what is 3 * TWICE(2)?

    It expands to 3 * 2 + 2, which is 8. With #define TWICE(x) ((x) + (x)) the result is 12; a constexpr function avoids the problem completely.
  2. 2. A header contains namespace net { #define PORT 8080 }. Where can PORT be used afterwards?

    The preprocessor runs before namespaces exist. A macro is visible from its #define to the end of the translation unit (or an #undef).
  3. 3. With #define SHOW(e) std::println("{} = {}", #e, (e)), what does SHOW(2 + 2) print?

    #e turns the argument's tokens into the string "2 + 2", while (e) is evaluated normally.
  4. 4. Which tool is best for writing a logging function that reports the caller's file and line in modern C++?

    The default argument is evaluated at the call site, so the function receives the caller's location without any macro.
  5. 5. You want to use std::expected when the library provides it and a fallback otherwise. What should you test?

    Feature-test macros describe individual features. Checking __cplusplus or a compiler version is less precise, because support for library features varies.

Summary

  • The preprocessor rewrites your source before compilation: it pastes #included files, expands macros and keeps or drops code with #if. It knows nothing about types or scopes; g++ -E shows its output.
  • Object-like macros ignore namespaces and scopes and have no type: use constexpr constants instead.
  • Function-like macros paste their arguments: parenthesize everything, never pass side effects, and prefer constexpr/inline functions or templates.
  • #x makes a string from an argument's text, a ## b pastes tokens, and __VA_ARGS__/__VA_OPT__ handle variable arguments.
  • #if/#ifdef/#elif (plus C++23 #elifdef) select code for platforms (_WIN32, __linux__), compilers and builds (-D, NDEBUG); use if constexpr for type-based decisions.
  • __cplusplus, __FILE__ and __LINE__ are predefined macros; __func__ and std::source_location give locations without macros.
  • #error stops a build, #warning (standard in C++23) prints a message, and #pragma gives compiler-specific instructions such as #pragma once.
  • Detect features with __has_include and feature-test macros like __cpp_lib_print, not with version numbers.

Next: Function Pointers and std::function