C: The Preprocessor

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: Dana🏷 Category: C Tutorial

The preprocessor is like reviewing blueprints before construction — before actual compilation begins, it expands macros, inserts header files, and prunes conditional branches, then hands the result to the compiler.

Reference entries in this section: #include else if #ifdef #ifndef #undef #endif #define

1. Preprocessing Pipeline

The C compilation process: source file → preprocessing → compilation → assembly → linking. The preprocessor runs before compilation, handling all directives that start with #.

You can use the -E flag to see only the preprocessed output:

BASH
gcc -E hello.c -o hello.i

2. #include Header Files

#include inserts the contents of the specified file verbatim at the current position.

(1) Two Forms

TEXT
#include <stdio.h>
#include "myheader.h"
💡 Tip: Use " " for your own headers and < > for standard library headers — this is the convention.

(2) Common Standard Headers

Header Main Content
stdio.h Input/output functions
stdlib.h Memory allocation, type conversion, random numbers
string.h String operations
math.h Math functions
ctype.h Character classification
assert.h Assert macro

3. #define Macro Definitions

(1) Object-Like Macros

Define named constants:

C
// Preprocessor directive
#define PI 3.14159265
// Preprocessor directive
#define MAX_SIZE 100
// Preprocessor directive
#define AUTHOR "WebTutorial"

// Variable declaration
double area = PI * 10 * 10;
int arr[MAX_SIZE];
// I/O operation
printf("Author: %s\n", AUTHOR);
⚠️ Note: Do not add a semicolon at the end of a macro definition! If you do, the semicolon becomes part of the substitution and may cause errors.

(2) Function-Like Macros

Macros with parameters look like functions but are text substitutions:

C
// Preprocessor directive
#define SQUARE(x) ((x) * (x))
// Preprocessor directive
#define MAX(a, b) ((a) > (b) ? (a) : (b))

// Variable declaration
int s = SQUARE(5);
// Variable declaration
int m = MAX(10, 20);
TEXT
25
20
💡 Tip: The preprocessor does simple text substitution — no type checking, no expression evaluation.


4. Macro Pitfalls and Parentheses

(1) Pitfall 1: Missing Parentheses Cause Precedence Errors

C
// Preprocessor directive
#define DOUBLE(x) x + x
TEXT
int result = DOUBLE(3) * 2;

After expansion this becomes 3 + 3 * 2, which yields 9 instead of the expected 12. Correct version:

C
// Preprocessor directive
#define DOUBLE(x) ((x) + (x))

(2) Pitfall 2: Parameters with Side Effects

C
// Preprocessor directive
#define SQUARE(x) ((x) * (x))
C
// Variable declaration
int n = 3;
// Variable declaration
int s = SQUARE(n++);

After expansion this becomes ((n++) * (n++)), incrementing n twice — undefined behavior.

⚠️ Note: Never pass expressions with side effects (like i++, func()) as macro arguments. Use inline functions or real functions instead.

(3) Pitfall 3: Macros in if-else Branches

C
// Preprocessor directive
#define CHECK(cond) if (cond) printf("yes\n")
C
// Conditional check
if (flag)
    CHECK(x);
// Else branch
else
    do_something();

After expansion, the else matches the macro's inner if, not the outer one — the classic dangling else problem. Wrap with do { ... } while(0):

C
// Preprocessor directive
#define CHECK(cond) do { if (cond) printf("yes\n"); } while(0)

▶ Example

▶ Try it Yourself
TEXT
max: 20
square: 25
after swap: x=20 y=10
double max: 3.5

5. Conditional Compilation

Conditional compilation lets the same source code produce different compiled output under different conditions. It's widely used for cross-platform support, debug switches, and feature trimming.

(1) #if / #elif / #else / #endif

C
// Preprocessor directive
#define PLATFORM 2

#if PLATFORM == 1
const char *os = "Windows";
#elif PLATFORM == 2
const char *os = "Linux";
#else
const char *os = "Unknown";
// Preprocessor directive
#endif

// I/O operation
printf("Platform: %s\n", os);
TEXT
Platform: Linux

(2) #ifdef / #ifndef

#ifdef checks whether a macro is defined; #ifndef checks whether it is not defined.

C
// Preprocessor directive
#define DEBUG

// Preprocessor directive
#ifdef DEBUG
// I/O operation
printf("Debug mode: x=%d\n", x);
// Preprocessor directive
#endif

// Preprocessor directive
#ifndef BUFFER_SIZE
// Preprocessor directive
#define BUFFER_SIZE 256
// Preprocessor directive
#endif
💡 Tip: #ifdef DEBUG is equivalent to #if defined(DEBUG), and #ifndef is equivalent to #if !defined(...).

(3) Debug Switch

C
// Preprocessor directive
#ifdef DEBUG
// Preprocessor directive
#define LOG(msg) printf("[DEBUG] %s:%d %s\n", __FILE__, __LINE__, msg)
#else
// Preprocessor directive
#define LOG(msg)
// Preprocessor directive
#endif

LOG("Variable initialized");

Compile with -DDEBUG to enable logging; without it, the program stays silent:

BASH
gcc -DDEBUG -o myapp myapp.c

▶ Example

▶ Try it Yourself
TEXT
Advanced features enabled
Concise output mode

6. Predefined Macros

The C standard predefines several useful macros:

Macro Meaning
__FILE__ Current source file name
__LINE__ Current line number
__DATE__ Compilation date
__TIME__ Compilation time
__func__ Current function name (C99)
__STDC__ Whether conforming to ANSI C standard
C
// I/O operation
printf("File: %s\n", __FILE__);
// I/O operation
printf("Line: %d\n", __LINE__);
// I/O operation
printf("Date: %s\n", __DATE__);
// I/O operation
printf("Time: %s\n", __TIME__);
// I/O operation
printf("Function: %s\n", __func__);
TEXT
File: main.c
Line: 5
Date: Jun 25 2026
Time: 14:30:00
Function: main
💡 Tip: Custom logging macros often combine predefined macros to output file names, line numbers, and other diagnostic information.


7. #undef to Cancel a Macro

#undef cancels a previous macro definition:

C
// Preprocessor directive
#define MAX_SIZE 100
// I/O operation
printf("%d\n", MAX_SIZE);
#undef MAX_SIZE

After #undef, MAX_SIZE is no longer a macro and can be redefined or used as a normal identifier.

▶ Example 3: Conditional Compilation with Include Guards

▶ Try it Yourself
C
// main.c — compile with -DDEBUG to see LOG output
#include <stdio.h>
#include "math_utils.h"

int main() {
    int x = 10, y = 20;
    LOG("Starting program");
    printf("MAX(%d, %d) = %d\n", x, y, MAX(x, y));
    printf("MIN(%d, %d) = %d\n", x, y, MIN(x, y));
    LOG("Done");
    return 0;
}

编译(带 DEBUG): gcc -DDEBUG main.c -o main && ./main 输出:

TEXT
[DEBUG] Starting program
MAX(10, 20) = 20
MIN(10, 20) = 10
[DEBUG] Done

Reference entries in this section: #include else if #ifdef #ifndef #undef #endif #define

❓ FAQ

Q Why are #ifndef and #define used in C++ header files?
A Header guards prevent double-inclusion — when a header is included twice (directly and via another header), the preprocessor skips the entire content on the second pass. The standard pattern is #ifndef HEADER_NAME, #define HEADER_NAME, code, then #endif. This is absolutely required for compile correctness.
Q Why use apparently meaningless do-while and if-else statements in macros?
A These are macro safety techniques. A do { ... } while(0) macro can be used as a single statement inside if (cond) MACRO(); else ... without breaking. The if (1) { ... } else trick also makes the macro behave like a single statement. Both are hacks for C's lack of statement-expression guarantees.
Q How do the likely/unlikely macros in the Linux kernel work?
A They wrap GCC's __builtin_expect intrinsic, which tells the compiler which branch is expected to be taken more often. likely(x) = __builtin_expect(!!(x), 1) tells the compiler x is probably true, optimizing instruction layout for the common case. This is purely a hint — no runtime branch prediction change.
Q What are the dangers of using pragma once?
A #pragma once is a non-standard header guard alternative. It can fail with unusual file paths (case-insensitive vs case-sensitive filesystems, symlinks, hardlinks) where the same physical file is opened via two different paths. It also slows compilation because the compiler must stat every file to detect duplicates. Use traditional include guards for 100% portability.
Q Is pragma once standard C?
A No. #pragma once is not part of the C standard and is not required of any conforming implementation. However, every major compiler (GCC, Clang, MSVC) supports it as an extension. For maximum portability across embedded or exotic compilers, stick with traditional include guards.
Q What is the difference between #include <> and #include ""?
A #include <file.h> searches system/include paths first (where standard library headers live). #include "file.h" searches the current file's directory first, then falls back to system paths. Use <> for standard library and third-party headers; use "" for your own project headers.
Q Why don't macro definitions end with a semicolon?
A Macros are text substitutions — the semicolon becomes part of the substitution text. #define FOO(x) bar(x); would expand to bar(42);; (double semicolon) or worse, break if used inside if (cond) FOO(x); else.... The do-while(0) pattern mentioned earlier solves this elegantly.
Q What is the difference between #ifdef and #if defined?
A Functionally identical, but #if defined(FOO) is more flexible because it supports logical operators: #if defined(FOO) && !defined(BAR). #ifdef can only check a single macro name. Use #if defined for anything beyond a simple single-check.

📖 Summary

📝 Exercises

  1. Define two versions of a SQUARE macro — one with parentheses and one without. Test both with SQUARE(2+3) and observe the result difference
  2. Use #ifdef DEBUG to implement a logging macro LOG(fmt, ...) that outputs the file name and line number in DEBUG mode and produces no output otherwise
  3. Use conditional compilation to implement cross-platform printing: print "Windows platform" on Windows, "Linux platform" on Linux, using #if defined(_WIN32) to detect the platform
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏