YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Building programsChapter 39 of 73

Preprocessing: preparing the source

Understand directives, configuration branches, and the difference between selecting source and choosing a runtime path.

5 min readIntermediateC17 baseline
Offline reading
In this chapter7 sections
0% through this chapter

Before ordinary C translation, preprocessing handles directives and macro replacement. This can select source, include declarations, or replace tokens. Following those steps explains why a preprocessor condition differs from a runtime condition.

1. Separate preparation from execution

Preprocessing is part of the translation model. Earlier phases handle source characters, backslash-newline splicing, and comments; directives and macro replacement then operate on preprocessing tokens. The implementation may combine phases internally, provided the required behavior is preserved. A separate executable called a preprocessor is a toolchain choice, not a language requirement.

Three different decisions
Preprocessing
Which tokens reach C analysis?
C translation
Are syntax and types valid?
Execution
Which runtime path is taken?
A conceptual model, not a requirement for three separate programs.

A directive begins with a # preprocessing token at the start of a preprocessing line; preceding whitespace is allowed. It is not an ordinary statement and needs no C statement semicolon. A backslash immediately followed by a newline joins physical lines before directives are processed. Avoid accidental trailing backslashes: they can change the next line’s meaning.

2. Choose a configuration before runtime

Complete C17 program
#include <stdio.h>

#ifndef CODEDILE_TRACE
#define CODEDILE_TRACE 0
#endif

int main(void)
{
#if CODEDILE_TRACE
    puts("trace enabled");
#else
    puts("trace disabled");
#endif
    return 0;
}

The default definition makes this program print trace disabled. With GCC, adding -DCODEDILE_TRACE=1 when compiling defines the macro for that invocation and selects the other branch. The command-line flag is a GCC interface; the #if directive is C. Neither branch asks the user to choose a setting while the program runs.

Use #ifdef NAME or #if defined(NAME) to ask whether a macro exists. #if NAME instead evaluates a preprocessing integer constant expression; in C17, after macro replacement and defined-processing, remaining ordinary identifiers are replaced by zero. Defining NAME as 0 therefore still satisfies #ifdef NAME. A local variable, an enum constant, or sizeof(int) is not a usable source of ordinary C type information for #if.

3. Excluded text differs from an unexecuted statement

Complete C17 program
#include <assert.h>

#if 0
int broken = ;
#endif

#define CODEDILE_LIMIT 7
int main(void)
{
    int limit = CODEDILE_LIMIT;
    assert(limit == 7);
    return 0;
}

The invalid C declaration is excluded before normal C analysis. Replacing #if 0 with if (0) would still require valid C syntax and appropriate type constraints in that branch. Excluded preprocessing groups are not arbitrary raw text: comments, strings, tokenization, and balanced conditional directives still matter. A comment that never closes can break preprocessing even inside an apparently disabled region.

4. Give directives specific jobs

DirectivePurpose
#includeMakes header/source contents participate in the current preprocessing translation unit.
#define, #undefStarts or ends a macro definition; it is not a variable assignment.
#errorRequires a diagnostic and prevents successful translation of an unacceptable build configuration.
#lineAdjusts the presumed source line/file information, often for generated code.
#pragmaControls specified implementation behavior; standard STDC forms have their own rules.

This next fragment intentionally requires a diagnostic and prevents successful translation when the required macro is absent. It is a build-rejection example, not a runnable program. #error is appropriate when silently using a guessed configuration would be misleading. Exact diagnostic text and later tool behavior depend on the implementation.

C17 · intentional build rejection
#ifndef CODEDILE_CAPACITY
#error "Define CODEDILE_CAPACITY before building this file"
#endif

__FILE__ and __LINE__ describe presumed source locations; __DATE__ and __TIME__ describe translation, not the current runtime clock. __STDC_VERSION__ identifies the claimed language revision, such as 201710L for C17 or 202311L for C23. It is not proof that an optional library feature is present. Do not invent application names beginning with reserved underscore patterns.

Primary references and further reading

Before you move on

  • Preprocessing handles directives and replacement before ordinary C semantic analysis.
  • A preprocessor condition selects source rather than testing a runtime object.
  • Configuration choices must leave valid declarations and compatible interfaces in the included source.
Keep these ideas separate
Defined macro / Nonzero macro value
A macro can be defined with the value zero, so checking existence differs from testing its numeric value.
Explain it in your own words

How does #if selecting source differ from an ordinary if choosing a runtime path?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

How does #if differ from an ordinary if?
Read the explanation for every choice
  1. Both select runtime branches in the same way.

    #if is handled during preprocessing rather than as an ordinary runtime statement.

  2. #if selects source during preprocessing; if selects a path in ordinary execution.

    ✓ Correct reasoning. Conditional inclusion determines which source tokens proceed into later translation.

  3. #if can inspect every runtime variable’s current value.

    Preprocessing condition rules do not provide access to future runtime object values.

C17

Quick reference from the earlier edition

Retained for existing section links and saved passages. The expanded explanation is above; documented corrections are recorded in the source review.

Preprocessing handles directives and macro replacement on preprocessing tokens before ordinary C semantic analysis. A directive starts with a # token at the beginning of a preprocessing line, allowing preceding whitespace. Directives control macro definitions, header inclusion, conditional compilation, and related behavior.

Main Preprocessor Directives

  • #define: Defines a macro for text substitution.
C17 · illustrative fragment
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
  • #undef: Undefines a previously defined macro.
C17 · illustrative fragment
#undef PI
  • #include: Includes the contents of a header file.
C17 · illustrative fragment
#include <stdio.h>      // System header
#include "myheader.h"   // User-defined header
  • #ifdef, #ifndef, #if, #elif, #else, #endif: Conditional compilation based on macro definitions.
C17 · illustrative fragment
#ifdef DEBUG
printf("Debug mode\n");
#endif
  • #error: Generates a compilation error with a custom message.
C17 · illustrative fragment
#ifndef PI
#error "PI is not defined"
#endif
  • #pragma: Controls implementation-defined behavior, except for standard-specified forms such as #pragma STDC FP_CONTRACT. #pragma once is a widely supported extension, not a standard C include guard.

  • #line: Changes the reported line number and filename for diagnostics.

Predefined Macros: The preprocessor provides several standard macros such as __FILE__, __LINE__, __DATE__, __TIME__, and __STDC__, which expand to the current filename, line number, compilation date, time, and standard conformance, respectively.

Example:

C17 · illustrative fragment
#include <stdio.h>
#define LIMIT 5

int main(void) {
    for (int i = 0; i < LIMIT; i++) {
        printf("%d\n", i);
    }
    return 0;
}

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 39 / 73

In this chapter

Preprocessing: preparing the source

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping