The Preprocessor & Macros

The Preprocessor & Macros in C: Before the compiler sees a single line of your code, a separate tool walks through it doing text substitution.

The Analogy: A Find-and-Replace Pass Before the Compiler Wakes Up

Before the compiler sees a single line of your code, a separate tool walks through it doing text substitution. It pastes in the contents of every #include, replaces every macro with its definition, and deletes the branches of #if blocks that do not apply. Only then does the real compiler start work, on a file that may look quite different from the one you wrote.

That tool is the preprocessor, and the important thing about it is what it does not know. It does not know about types, scopes, functions or statements. It moves tokens around. This is why a macro can do things no function can — refer to the file and line of its own call site, or compile itself out of existence entirely — and equally why a badly written macro fails in ways that make no sense until you look at the substituted text.

You can always look. gcc -E main.c prints exactly what the compiler receives, and it is the fastest way to end an argument about what a macro expanded to.


Syntax or Core Structure

#include <stdio.h>

#define MAX_USERS 100
#define PI 3.14159265358979
#define SQUARE(x) ((x) * (x))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define LOG(fmt, ...) printf("[log] " fmt "\n", __VA_ARGS__)

int main(void) {
    printf("MAX_USERS = %d\n", MAX_USERS);
    printf("area of r=2: %.4f\n", PI * SQUARE(2));
    printf("SQUARE(3 + 1) = %d\n", SQUARE(3 + 1));
    printf("MIN(7, 4) = %d\n", MIN(7, 4));
    LOG("started with %d users", 3);
    printf("%s line %d\n", __FILE__, __LINE__);
    return 0;
}

Output:

MAX_USERS = 100
area of r=2: 12.5664
SQUARE(3 + 1) = 16
MIN(7, 4) = 4
[log] started with 3 users
main.c line 15

__FILE__ is the path exactly as it was handed to the compiler, and __LINE__ is 15 because that printf is the fifteenth line of the file. Neither could be produced by a function: a function only ever knows where it was written.

SQUARE(3 + 1) giving 16 rather than 7 is entirely down to those inner parentheses. ((x) * (x)) expands to ((3 + 1) * (3 + 1)); the naive x * x would expand to 3 + 1 * 3 + 1, which multiplication-before-addition turns into 7.

The directives worth knowing

DirectiveWhat it does
#include "f.h" / <f.h>pastes the file in; quotes search your project first, angle brackets the system paths
#define / #undefcreate or remove a macro
#if / #elif / #else / #endifkeep one branch, delete the rest before compiling
#ifdef X / #ifndef Xshorthand for #if defined(X) / #if !defined(X)
#error "msg"stop the build with a message
#pragmacompiler-specific instruction, e.g. #pragma once

Because #if runs before compilation, it can only see integer constants and other macros. It cannot evaluate sizeof, cannot see an enum constant, and treats any identifier it does not recognise as 0.


Technical Depth: Text Substitution and Its Consequences

Double evaluation: the flaw a function does not have

#define MAX(a, b) ((a) > (b) ? (a) : (b))

int i = 5, j = 3;
int m = MAX(i++, j);        /* expands to ((i++) > (j) ? (i++) : (j)) */

Whichever branch is taken, i++ appears twice in the expansion and may run twice. The macro is perfectly parenthesised and still wrong, because parentheses cannot stop an argument being duplicated. A function evaluates each argument exactly once:

static inline int max_int(int a, int b) { return a > b ? a : b; }

So the rule is: if a plain function will do, write a function. static inline in a header gives you the same absence of call overhead with type checking, single evaluation, and a name a debugger can show you.

NeedUse
A named constantenum for integers, const for anything else
A small computationstatic inline function
The caller's file or linemacro (nothing else can)
Code that must vanish in release buildsmacro plus #if
A wrapper that works for several typesmacro, carefully

Multi-statement macros need do { } while (0)

/* Broken: the else has nothing to attach to. */
#define RESET(p, n) (p)->count = 0; (p)->total = 0

if (full) RESET(box, 4);
else keep(box);                 /* error: unexpected else */

/* Correct: one statement, and the trailing semicolon at the call site is natural. */
#define RESET(p, n)          \
    do {                     \
        (p)->count = 0;      \
        (p)->total = 0;      \
    } while (0)

The backslash at the end of each line joins it to the next before anything else happens — and it must be the very last character, since a single trailing space after it breaks the continuation with an error that points at the wrong line. do { ... } while (0) is a single statement that runs once, so it works in every position a statement can appear, including an unbraced if.

Stringify and paste

#define STR(x) #x                      /* # turns a token into a string literal */
#define XSTR(x) STR(x)                 /* extra layer expands x first */
#define CONCAT(a, b) a##b              /* ## glues two tokens together */

#define VERSION 7
printf("%s %s\n", STR(VERSION), XSTR(VERSION));   /* prints: VERSION 7 */

int CONCAT(user, _count) = 3;                      /* declares user_count */

# freezes the argument text before expansion, which is why the double layer is needed to stringify a macro's value. Both operators are how test frameworks print the expression that failed, as assert does.

Include guards

#ifndef INVENTORY_H
#define INVENTORY_H
/* declarations */
#endif

Without this, a header included twice — directly and again through another header — defines every struct and typedef twice, which is an error. The guard makes the second inclusion expand to nothing. #pragma once does the same job in one line and is supported by every mainstream compiler, but it is not in the standard; the #ifndef form works everywhere.

Conditional compilation

#if defined(DEBUG) && DEBUG > 1
    verify_invariants(state);
#elif defined(DEBUG)
    check_bounds(state);
#else
    /* nothing in release builds */
#endif

#if __STDC_VERSION__ < 199901L
#  error "this code needs C99 or later"
#endif

Set these from the build line — gcc -DDEBUG=2 ... — so one source tree produces different builds. Code inside a false branch is deleted before compilation, so it costs nothing at run time; it is also never checked, which is why a rarely-enabled branch tends to stop compiling without anyone noticing.

Useful predefined names: __FILE__, __LINE__, __DATE__, __TIME__, __STDC_VERSION__, and NDEBUG which switches assert off. __func__ looks like a macro but is a predefined identifier holding the current function's name, so it works inside a function and nowhere else.


Real World Example: A Logging Header With Compile-Time Levels

This is the case where a macro is not a shortcut but the only option: the log has to report the file and line of the call site, and the disabled levels have to disappear from the binary entirely.

/* ---------- logging.h ---------- */
#ifndef LOGGING_H
#define LOGGING_H

#include <stdio.h>

#define LOG_LEVEL_NONE  0
#define LOG_LEVEL_ERROR 1
#define LOG_LEVEL_INFO  2
#define LOG_LEVEL_DEBUG 3

#ifndef LOG_LEVEL                      /* let the build line override it */
#  define LOG_LEVEL LOG_LEVEL_INFO
#endif

#define LOG_AT(level, tag, fmt, ...)                         \
    do {                                                     \
        if ((level) <= LOG_LEVEL)                            \
            fprintf(stderr, "[%-5s] %s:%d: " fmt "\n",       \
                    tag, __FILE__, __LINE__, __VA_ARGS__);    \
    } while (0)

#define LOG_ERROR(fmt, ...) LOG_AT(LOG_LEVEL_ERROR, "error", fmt, __VA_ARGS__)
#define LOG_INFO(fmt, ...)  LOG_AT(LOG_LEVEL_INFO,  "info",  fmt, __VA_ARGS__)
#define LOG_DEBUG(fmt, ...) LOG_AT(LOG_LEVEL_DEBUG, "debug", fmt, __VA_ARGS__)

#define ARRAY_LEN(a) (sizeof (a) / sizeof (a)[0])

#endif
/* ---------- main.c ---------- */
#include "logging.h"

int main(void) {
    int codes[] = { 12, 7, 40, 3 };

    LOG_INFO("checking %zu codes", ARRAY_LEN(codes));
    for (size_t i = 0; i < ARRAY_LEN(codes); i++) {
        LOG_DEBUG("codes[%zu] = %d", i, codes[i]);
        if (codes[i] > 30)
            LOG_ERROR("code %d out of range", codes[i]);
    }
    LOG_INFO("done with %d error(s)", 1);
    return 0;
}

Built with no options, LOG_LEVEL defaults to LOG_LEVEL_INFO, so the debug lines are compiled out:

gcc -std=c17 -Wall -Wextra -o app main.c

Output:

[info ] main.c:6: checking 4 codes
[error] main.c:10: code 40 out of range
[info ] main.c:12: done with 1 error(s)

The same source, rebuilt with gcc -std=c17 -DLOG_LEVEL=3 -o app main.c:

Output:

[info ] main.c:6: checking 4 codes
[debug] main.c:8: codes[0] = 12
[debug] main.c:8: codes[1] = 7
[debug] main.c:8: codes[2] = 40
[error] main.c:10: code 40 out of range
[debug] main.c:8: codes[3] = 3
[info ] main.c:12: done with 1 error(s)

Every debug line reports 8 because that is where the call is written, and the error reports 10 — the line numbers come from the call sites, not from inside logging.h. With -DLOG_LEVEL=0 the program prints nothing at all.

Five details are doing real work here:

  1. if ((level) <= LOG_LEVEL) compares two compile-time constants. Any optimiser deletes the whole branch, so a disabled log costs nothing — not even the test — while the source stays readable.
  2. do { ... } while (0) keeps it a single statement. Without it, if (x) LOG_ERROR(...); else ... would not compile, and the if inside the macro would silently steal the caller's else.
  3. #ifndef LOG_LEVEL gives a default without preventing an override. The build line wins; the header only fills the gap.
  4. "[%-5s] %s:%d: " fmt relies on adjacent string literals being joined. Because fmt must be a literal, the pieces merge into one format string at compile time — another thing a function could not do.
  5. ARRAY_LEN is used at the call site, not passed a pointer. It works only where the real array is in scope; inside a function taking int * it would compute a pointer size divided by 4. That limitation is inherent to text substitution, and a comment in the header should say so.

One portability note: __VA_ARGS__ in C99 requires at least one variadic argument, so LOG_INFO("done") with no extra values is a syntax error. Pass a dummy value, add a separate LOG_INFO0, or use C23's __VA_OPT__(,) to make the comma conditional.


Common Mistakes

  1. Missing parentheses. #define SQUARE(x) x * x makes SQUARE(3 + 1) expand to 3 + 1 * 3 + 1, which is 7. Wrap every parameter and the whole body: ((x) * (x)).
  2. A semicolon in the definition. #define MAX_USERS 100; turns int a[MAX_USERS]; into int a[100;];. Object-like macros never end in a semicolon.
  3. Multi-statement macros without do { } while (0). Two statements separated by a semicolon break any unbraced if, and an if inside a bare macro captures the caller's else.
  4. Arguments evaluated more than once. MAX(i++, j) duplicates i++ in the expansion. Parentheses cannot fix this; use a static inline function instead.
  5. Lowercase macro names that collide. A macro called max or min replaces every occurrence of that word in every file that includes the header, including inside other libraries' declarations. Use SHOUTING_CASE and a project prefix.
  6. A header with no include guard. Included twice — often indirectly — it redefines every struct and typedef. Add the #ifndef guard to every header, without exception.
  7. Expecting #if to understand C. #if sizeof(int) == 4 does not work, and an unknown identifier in #if quietly becomes 0, so #if LOG_LEVEL with LOG_LEVEL misspelled reads as false with no warning. Compile with -Wundef to be told.
  8. A typo in an #ifdef name. #ifdef DEUBG disables the entire block permanently and nothing complains, because a name that is simply not defined is a legitimate state.

Best Practices

  • Reach for static inline first, and use a macro only when you need the call site's file and line, code that vanishes in release builds, or type-independent text substitution.
  • Prefer enum for related integer constants and const for everything else; both are visible to the debugger and obey scope.
  • Parenthesise every parameter and the full body of every function-like macro.
  • Wrap multi-statement macros in do { ... } while (0), with the backslash as the last character on each line.
  • Name macros in upper case with a project prefix, and mention in a comment when a macro evaluates an argument more than once.
  • Guard every header, and keep #defines that are only needed by one .c file inside that file.
  • Drive conditional compilation from the build line with -D, provide a default with #ifndef, and build the rarely-enabled configurations in CI so they do not rot.
  • When a macro misbehaves, run gcc -E and read the expansion instead of guessing.

Practice Exercises

  1. Break a macro and then fix it. Define #define SQUARE(x) x * x and print SQUARE(3 + 1), SQUARE(2) * SQUARE(2) and 10 / SQUARE(2). Predict each result before running, record what you actually get, then add the parentheses and repeat. Confirm your explanation against gcc -E output for all three expressions.
  2. Demonstrate double evaluation. Write MAX(a, b) as a macro and max_int as a static inline function. Call each with i++ where i starts at 5, print i afterwards, and explain the difference. Then find a case where the macro version also produces the wrong result, not just a wrong side effect.
  3. A three-level assert. Build check.h with CHECK(cond) that, when CHECK_ENABLED is non-zero, prints the failing condition as text using #, plus __FILE__, __LINE__ and __func__, and returns -1 from the calling function. Use do { } while (0) and make it work inside an unbraced if. Verify that with -DCHECK_ENABLED=0 the checks vanish, then compare your macro with what assert from <assert.h> does under -DNDEBUG.
  4. A guard, a paste, and a build matrix. Write shapes.h with an include guard, and include it twice from main.c to prove the guard works — then comment the guard out and record the exact error. Add #define DECLARE_PAIR(type, name) type name##_min; type name##_max; and use it to declare int score_min; int score_max;, checking with gcc -E that the pasted names are what you intended. Finally build the file with -DLOG_LEVEL=0, =1 and =3 and confirm each produces the output you predicted.