Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 135 ยท Preprocessor

The Preprocessor

Learn how the C preprocessor works: directives, #include with brackets or quotes, #define and #undef, #error and #warning, and gcc -E output.

Before the C compiler sees a single statement of your program, another tool has already been through the file: the preprocessor. It handles every line that starts with #. It pastes header files into your code, replaces names you defined with #define, and keeps or drops whole blocks of code depending on conditions. Its output, a single long stream of plain C, is what the compiler proper actually translates.

The preprocessor doesn't understand C. It knows nothing about types, variables or scopes; it works on tokens (words, numbers, punctuation) and does text-like substitution. That makes it powerful and simple, and also the source of some famously confusing bugs. This chapter starts with the big picture: what the preprocessor does, #include, simple #define constants, and how to look at its output. The following lessons cover Macros, Conditional Compilation and Predefined Macros and assert.

Where the preprocessor fits

You met the build pipeline in How C Works: preprocess, compile, assemble, link. The preprocessing step itself runs in a few phases:

  1. Line endings are normalized and line splices are joined: a backslash at the very end of a line glues it to the next line.
  2. The text is split into preprocessing tokens, and every comment is replaced by a single space.
  3. Directives are executed and macros are expanded. #include files go through the same steps recursively.
  4. Adjacent string literals are joined: "Hello, " "world" becomes "Hello, world".

The result is called a translation unit: your .c file with all its headers pasted in, all macros expanded and all directives gone. On a typical system, a 10-line program that includes <stdio.h> turns into many hundreds of lines.

Directives

A directive is a line whose first non-blank character is #. Directives end at the end of the line (use a backslash to continue one), and they aren't statements, so they don't end with a semicolon. Here are all of them:

Directive Purpose Lesson
#include Paste another file here this one
#define, #undef Define or remove a macro this one, Macros
#if, #ifdef, #ifndef, #elif, #elifdef, #elifndef, #else, #endif Keep or drop code Conditional Compilation
#error, #warning Stop with an error, or print a warning this one
#pragma Compiler-specific instructions Conditional Compilation
#line Change the reported line number and file name Predefined Macros
#embed Include a binary file's bytes (C23) Conditional Compilation
# alone The null directive; does nothing

#elifdef, #elifndef, #warning and #embed became standard in C23; GCC and Clang supported #warning as an extension for decades.

#include: pasting files

#include replaces the directive with the entire contents of another file. It really is that literal: the preprocessor reads the file and inserts its text in place. Headers contain declarations, such as the prototype of printf, so after inclusion the compiler knows those names exist.

There are two forms:

C
#include <stdio.h>      /* system and library headers */
#include "list.h"       /* your own project's headers */
  • Angle brackets search the compiler's system include directories (like /usr/include on Linux) plus any directories you add with -I.
  • Double quotes first search the directory of the file that contains the #include, then fall back to the same places as angle brackets.

The rule of thumb: angle brackets for the standard library and installed libraries, quotes for files in your project. Because #include pastes text, a header included twice gets pasted twice, which can cause redefinition errors. Conditional Compilation shows the include guards that prevent this, and Multi-File Programs shows how to split a program into headers and source files.

Our editor compiles a single main.c, so you can include standard headers but not your own files. This example uses several standard headers; each one is pasted in before compilation:

C Standard headers in action

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 scanf or fgets), it gets the next line from this box.

Delete the #include <string.h> line and run it again: GCC stops with error: implicit declaration of function 'strlen' and suggests the header to include, because without the paste the compiler never saw its prototype.

#define: object-like macros

#define NAME replacement creates a macro. From that point on, every time the token NAME appears, the preprocessor replaces it with the replacement tokens. A macro without parentheses is called object-like, and its most common use is naming a constant:

C Object-like macros

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 scanf or fgets), it gets the next line from this box.

After preprocessing, the compiler sees printf("%s! Up to %d users.\n", "Welcome", 100); and char buffer[(100 * 4)];. Notice:

  • Replacement happens only for whole tokens. MAX_USERS inside a string literal is part of the string token, so it stays untouched; so would a longer name like MAX_USERS_PER_ROOM.
  • A macro's replacement can use other macros (BUFFER_SIZE uses MAX_USERS). They're expanded when the macro is used, not when it's defined.
  • BUFFER_SIZE has parentheses around its value. Without them, BUFFER_SIZE / 2 would become 100 * 4 / 2, which happens to work here, but a definition like #define TOTAL 10 + 5 turns TOTAL * 2 into 10 + 5 * 2, which is 20, not 30. The rule "always parenthesize macro values that contain operators" is explained fully in Macros.
  • There's no = and no semicolon. #define MAX_USERS = 100; would replace MAX_USERS with = 100;, producing baffling errors far from the definition.

Macros are by convention written in UPPER_CASE so readers can tell that something unusual is going on. For typed constants, C also has const, enum and C23 constexpr, compared in Constants. Prefer those when you can: they have types and scopes, and debuggers know them.

Macros ignore scope; #undef ends them

A macro is visible from its #define to the end of the translation unit, regardless of braces, functions or blocks. #undef removes it, after which you can define it again with a different value:

C Macros have no scope

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 scanf or fgets), it gets the next line from this box.

Even though #define LIMIT 10 is written inside main, it isn't "local" to main: the preprocessor doesn't know what a function is. It just processes lines from top to bottom. print_limit is defined after the final #undef, so LIMIT would be an unknown identifier there. If you redefine a macro without #undef and with a different value, GCC warns 'LIMIT' redefined (the standard calls it a constraint violation); defining it again with exactly the same tokens is allowed.

Macros also can't be shadowed. If a header defines #define count 5 (badly named!), every variable called count in your file becomes 5. That's why macro names are uppercase and libraries prefix them (SDL_, CURL_).

Defining macros from the command line

Compilers let you define macros without touching the source, with -D. This is how builds switch features or set version numbers:

Terminal
gcc -DMAX_USERS=500 -DDEBUG main.c -o app     # like #define MAX_USERS 500 and #define DEBUG 1
gcc -UDEBUG main.c -o app                      # like #undef DEBUG

A common pattern provides a default that the build can override:

C
#ifndef MAX_USERS
#define MAX_USERS 100       /* default if not given with -D */
#endif

Our editor doesn't let you add compiler flags, but you can simulate -D by putting a #define at the top of the file.

#error and #warning

#error stops compilation with your message. #warning (standard since C23) prints a warning and continues. Both are mostly used inside conditional blocks to catch bad configurations early:

C Stopping or warning at compile time

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 scanf or fgets), it gets the next line from this box.

The program compiles and runs, and GCC prints warning: #warning "USE_OLD_API is deprecated and will be removed" [-Wcpp] above the output. Change BUFFER_SIZE to 8 and the build fails with error: #error "BUFFER_SIZE must be at least 16" before any C code is compiled. You'll write many checks like this in Conditional Compilation.

Line continuation

A backslash as the very last character of a line joins it with the next line, before tokens are formed. It's essential for long macros:

C
#define WELCOME_TEXT \
    "Hello and welcome to the program. " \
    "Type a command to begin."

The three lines become one #define, and the two string literals are joined in a later phase. Watch out for spaces after the backslash: \ followed by a newline isn't a continuation, and GCC warns backslash and newline separated by space.

Viewing the preprocessed output

When a macro does something surprising, look at what the compiler actually receives. gcc -E runs only the preprocessor and prints the translation unit:

Terminal
gcc -E main.c              # print the preprocessed code to the terminal
gcc -E main.c -o main.i    # save it to main.i (the usual extension)
gcc -E -P main.c           # without the "# 12 \"main.c\"" line markers
gcc -dM -E main.c          # list every macro that is defined at the end

For a file like this one:

C
#define SQUARE_SIDE 7
#define AREA (SQUARE_SIDE * SQUARE_SIDE)

int area(void) {
    return AREA;    /* comment */
}

gcc -E -P prints:

TEXT
int area(void) {
    return (7 * 7);
}

The #define lines are gone, the macros are replaced, and the comment has vanished. With #include <stdio.h> at the top, you'd see hundreds of lines of declarations first, which is a good reminder of how much a single include pulls in. Clang has the same options, and MSVC uses /E or /P.

-dM -E is useful for discovering what your compiler predefines: running gcc -dM -E - < /dev/null on Linux lists hundreds of macros like __x86_64__ and __GNUC__. Predefined Macros covers the ones the standard guarantees.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With #define TOTAL 10 + 5, what does printf("%d", TOTAL * 2); print?

    The preprocessor pastes the tokens, so the expression becomes 10 + 5 * 2. Multiplication goes first, giving 20. Parentheses in the definition would fix it.
  2. 2. What does the preprocessor do with MAX inside "MAX users" when MAX is a macro?

    Macro replacement works on whole tokens. The string literal is one token, so text inside it is never replaced.
  3. 3. A #define LIMIT 10 appears inside the body of main. Where can LIMIT be used?

    Macros ignore C scope. A macro exists from its definition to the end of the translation unit or to an #undef.
  4. 4. What is the main difference between #include <file.h> and #include "file.h"?

    Quotes look in the directory of the current file first and then in the system paths; angle brackets search only the system and -I paths. Use quotes for your own headers.
  5. 5. Which command shows the code exactly as the compiler receives it after preprocessing?

    -E stops after preprocessing and prints the result. -S produces assembly and -c an object file.

Summary

  • The preprocessor runs before compilation and handles every line that starts with #; it works on tokens, not on C semantics.
  • #include pastes a file's text: <...> for system headers, "..." for your own (searched in the current directory first).
  • #define NAME value replaces the token NAME everywhere after it; no =, no semicolon, parentheses around expressions.
  • Macros ignore scope; #undef removes them. Compilers define macros from the command line with -D.
  • #error stops the build with a message; #warning (C23) prints one and continues.
  • A trailing backslash continues a line, and gcc -E (with -P or -dM) shows what the preprocessor produced.

Next: Macros