Skip to main content

Conditional Compilation

beginner12 min readLesson 62 of 148

#if, #ifdef, and the include guard that stops double definitions.

The include guard

Every header wears this armor:

#ifndef GEOM_H
#define GEOM_H

/* declarations live here */

#endif

If the header is included twice, the second pass finds GEOM_H already defined and skips the body โ€” no duplicate definitions. Without guards, two #includes of one header that defines anything = compile error.

#ifdef / #ifndef for platform or debug switches

#define DEBUG 1

#ifdef DEBUG
    fprintf(stderr, "x=%d\n", x);
#endif

The debug line exists in the compiled program ONLY when DEBUG is defined. This is how C code bases support many platforms and configurations from one source tree.

#if with constant expressions

#if MAX_SCORE > 50
#   define GRADE_SCALE "percent"
#else
#   define GRADE_SCALE "raw"
#endif

What the preprocessor is NOT

It knows nothing of C types, variables, or scopes. It is a text machine. Everything it produces must still be legal C โ€” the errors you see after expansion point at the result, not the macro call.

Now practice

Organization Practicestatic helpers, do-while macro wrappers, and guarded declarations.3 challenges ยท ยท ~15 min