Skip to content

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.

Beginner 15 min read·Lesson 32 of 37 in C Programming

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.

Predefined macroExpands to
__FILE__current file name (string)
__LINE__current line number (int)
__func__current function name (not a macro, but a predefined identifier)
__DATE__ / __TIME__compilation date / time
__STDC_VERSION__201112L for C11, 201710L for C17

Syntax

C
#include <stdio.h>
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#ifdef DEBUG
# define LOG(msg) printf("[%s:%d] %s\n", __FILE__, __LINE__, msg)
#else
# define LOG(msg) ((void)0)
#endif
  • 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 -DDEBUG to enable the debug branch.

Code examples

Safe and unsafe macros

C
#include <stdio.h>
#define BAD_SQ(x) x * x
#define SQ(x) ((x) * (x))
int main(void) {
printf("%d %d\n", BAD_SQ(2 + 3), SQ(2 + 3));
printf("%d\n", 100 / SQ(5));
return 0;
}
Output
11 25
4

BAD_SQ(2 + 3) expands to 2 + 3 * 2 + 3 = 11.

Stringising and predefined macros

C
#include <stdio.h>
#define SHOW(expr) printf(#expr " = %d\n", (expr))
int main(void) {
int a = 6, b = 7;
SHOW(a * b);
SHOW(a > b);
printf("line %d in %s()\n", __LINE__, __func__);
return 0;
}
Output
a * b = 42
a > b = 0
line 8 in main()

More examples

Conditional compilation and the double-evaluation trap

C
#include <stdio.h>
#define VERSION 2
#define MAX(a, b) ((a) > (b) ? (a) : (b))
static inline int max_int(int a, int b) { return a > b ? a : b; }
int calls = 0;
int next(void) { return ++calls * 10; }
int main(void) {
#if VERSION >= 2
printf("using version 2 features\n");
#else
printf("using legacy features\n");
#endif
#ifndef DEBUG
printf("debug logging is off\n");
#endif
calls = 0;
int m1 = MAX(next(), 5); /* next() may run twice */
printf("macro: max=%d, next() called %d times\n", m1, calls);
calls = 0;
int m2 = max_int(next(), 5); /* exactly once */
printf("inline: max=%d, next() called %d times\n", m2, calls);
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
printf("compiled as C11 or later\n");
#endif
return 0;
}
Output
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 >= 2 is evaluated by the preprocessor; only one printf survives into the compiled code.
  • #ifndef DEBUG is true because we compiled without -DDEBUG.
  • MAX(next(), 5) expands to ((next()) > (5) ? (next()) : (5)).
  • The first next() returns 10; 10 > 5 is true, so the second operand is evaluated — calling next() again, which returns 20. The macro yields 20 and next() 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 #if checks __STDC_VERSION__, which is 201112L or greater for C11 and later.

Expected output

Running “Conditional compilation and the double-evaluation trap” prints exactly:

TextOutput
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

Practical applications

  • Cross-platform code uses #ifdef _WIN32 to select Windows APIs.
  • Assertion macros (assert) report __FILE__ and __LINE__ on failure.
  • Feature flags compiled in or out with -D options control product editions.

Best practices

  • Parenthesise every macro parameter and the whole replacement.
  • Prefer const variables, enums and static inline functions over macros.
  • Use upper-case names for macros so readers know text substitution is happening.

Common mistakes

Space before the macro parameter list

Avoid

#define SQ (x) ((x) * (x))

Prefer

#define SQ(x) ((x) * (x))

With a space, SQ becomes an object-like macro whose text is (x) ((x) * (x)).

Side effects in macro arguments

Avoid

int r = SQ(i++);

Prefer

int t = i++;
int r = SQ(t);

The argument is pasted twice, so i is incremented twice in one expression — undefined behaviour.

Important notes

  • #pragma once is 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/#ifdef for conditional compilation and include guards.

Try it yourself

  1. 1
    Write a SWAP(type, a, b) macro using a do { ... } while (0) block and explain why that wrapper is used.
  2. 2
    Add a DEBUG_PRINT macro 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?
Practise this topic