Module 8 · Files, the Preprocessor and Program Organisation — topic 2 of 4
Preprocessor Directives
Before compilation, the preprocessor handles #include, #define, conditional compilation and macros. Learn object-like and function-like macros, their pitfalls, include guards and predefined macros.
Learning objectives
- Write object-like and function-like macros safely
- Use #if, #ifdef and #ifndef for conditional compilation
- Use predefined macros such as __FILE__ and __LINE__
Definition
The C preprocessor is a text-transformation phase that runs before compilation. Lines beginning with # are directives that include files, define and expand macros, and conditionally include or exclude source text.Introduction
The preprocessor knows nothing about C types or variables — it works on text. #include pastes a file in, #define replaces names with text, and #if keeps or drops lines before the compiler ever sees them.
Used well, it lets one source file build for Windows and Linux, include debug logging only in debug builds, and avoid repeating constants. Used carelessly, macros produce baffling bugs because their arguments are pasted textually.
Why it matters
Every header file uses include guards; every portable library uses conditional compilation. You will read and write these constantly.
Macro pitfalls (missing parentheses, double evaluation) are classic exam and interview questions.
Detailed explanation
#include <file> searches the system include paths; #include "file" searches the current directory first. The file's text replaces the directive.
Object-like macro: #define MAX 100. Function-like macro: #define SQUARE(x) ((x) * (x)) — parenthesise each parameter and the whole body. There must be no space between the name and (.
Macro arguments are substituted as text and may be evaluated more than once: SQUARE(i++) increments i twice — undefined behaviour. Prefer static inline functions for anything non-trivial.
Conditional compilation: #if, #elif, #else, #endif, #ifdef NAME, #ifndef NAME, and defined(NAME). Define a macro from the command line with gcc -DDEBUG.
Operators: #x turns a parameter into a string literal; a##b pastes tokens. #undef removes a definition; #error "msg" stops compilation with a message.
Syntax
- A directive ends at the end of the line; continue it with a backslash.
((void)0)makes a disabled macro a harmless expression.- Compile with
-DDEBUGto enable the debug branch.
Code examples
Safe and unsafe macros
11 25 4
BAD_SQ(2 + 3) expands to 2 + 3 * 2 + 3 = 11.
Stringising and predefined macros
a * b = 42 a > b = 0 line 8 in main()
More examples
Conditional compilation and the double-evaluation trap
using version 2 features debug logging is off macro: max=20, next() called 2 times inline: max=10, next() called 1 times compiled as C11 or later
Step-by-step explanation
#if VERSION >= 2is evaluated by the preprocessor; only oneprintfsurvives into the compiled code.#ifndef DEBUGis true because we compiled without-DDEBUG.MAX(next(), 5)expands to((next()) > (5) ? (next()) : (5)).- The first
next()returns 10;10 > 5is true, so the second operand is evaluated — callingnext()again, which returns 20. The macro yields 20 andnext()ran twice. max_int(next(), 5)evaluates its argument once before the call:next()returns 10, and the function returns max(10, 5) = 10.- The final
#ifchecks__STDC_VERSION__, which is 201112L or greater for C11 and later.
Expected output
Running “Conditional compilation and the double-evaluation trap” prints exactly:
Practical applications
- Cross-platform code uses
#ifdef _WIN32to select Windows APIs. - Assertion macros (
assert) report__FILE__and__LINE__on failure. - Feature flags compiled in or out with
-Doptions control product editions.
Best practices
- Parenthesise every macro parameter and the whole replacement.
- Prefer
constvariables, enums andstatic inlinefunctions over macros. - Use upper-case names for macros so readers know text substitution is happening.
Common mistakes
Space before the macro parameter list
Avoid
Prefer
With a space, SQ becomes an object-like macro whose text is (x) ((x) * (x)).
Side effects in macro arguments
Avoid
Prefer
The argument is pasted twice, so i is incremented twice in one expression — undefined behaviour.
Important notes
#pragma onceis a widely supported but non-standard alternative to include guards.- The preprocessor output can be inspected with
gcc -E file.c.
Key takeaways
- The preprocessor transforms text before compilation.
- Parenthesise macro parameters and bodies; beware double evaluation.
- Use
#if/#ifdeffor conditional compilation and include guards.
Try it yourself
- 1Write a
SWAP(type, a, b)macro using ado { ... } while (0)block and explain why that wrapper is used. - 2Add a
DEBUG_PRINTmacro to a program that prints only when compiled with-DDEBUG.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
5 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is the difference between `#include <file.h>` and `#include "file.h"`?
- ModerateWhat is printed?
- ModerateWhat is printed?