Section 15.16

Conditional compilation

Definition

Conditional compilation is the choice, made before a compiler translates a program, of which parts of the source text are compiled, based on configuration values. In C and C++ the preprocessor, the stage that runs first, makes the choice with directives such as #if, #ifdef, #else and #endif. Text in a group whose condition is false is deleted: it is never compiled and is absent from the program that is built. The C standard calls this conditional inclusion. Build systems make the same kind of choice for whole files.

The idea

One source file often serves several products: a debug build and a release build, two circuit boards, a build with logging and one without. Copying the file for each product would let the copies drift apart. Conditional compilation keeps one file and marks the parts that differ, so each build compiles only its own parts. The price is that the file no longer shows the program. A reviewer who reads a function with two versions under #if sees both versions, but a given image contains at most one. Which one depends on values that may live in another file, on the compiler’s command line, or in a header that the build generates.

The preprocessor works on text, before types and functions exist for the compiler. A deleted group is not checked at all: it may contain code that would not even compile, and no build that deletes it will notice.

How it works

In C the preprocessor reads the file from top to bottom, together with every header it includes, and evaluates each directive with the macro definitions in force at that line.

  1. Collect definitions. Macros come from #define lines, in the order in which they are read, and from the compiler command line. With GCC §12.17 (GNU Compiler Collection, where GNU stands for GNU’s Not Unix) and Clang, -DFEATURE defines FEATURE as 1, -DFEATURE=2 gives it the value 2, and -UFEATURE removes it. An #undef line removes a definition in the text.

  2. Evaluate a condition. #ifdef FEATURE asks only whether FEATURE is defined at that line, whatever its value. #if followed by an expression expands the macros in the expression, except a name that follows defined, replaces each defined FEATURE or defined(FEATURE) by 1 or 0, replaces every identifier still left by 0, and evaluates the result as an integer; a nonzero result means true.

  3. Select one group. In a chain #if, #elif, …, #else, #endif, the first group whose condition is true is kept and every other group is deleted. Inside a deleted group the preprocessor only follows nested directives, so that it can find the matching #endif; it checks nothing else.

  4. Compile. The compiler proper receives the text that remains.

The values that decide a condition can come from places the reader of the source file never sees.

The reliable record of what a build compiled comes from the build itself.

  1. Recover the exact compile command that the build used for the file. Many build systems can write these commands to a file named compile_commands.json.

  2. Rerun the command with -E added, which makes GCC or Clang stop after preprocessing and print the text the compiler proper would receive. The deleted groups are absent from that text. Adding -dM as well prints instead every macro still defined at the end of preprocessing, with its value.

  3. Check that the generated headers and include directories are those of the build in question, not of a later build in the same directory.

  4. Confirm the result in the image, for example by finding a symbol name, a text string or a code sequence that only one of the groups produces.

Worked example

A generated header config.h contains #define LOG_PACKETS 0, which its author meant as “logging off”. A source file that includes config.h contains two tests:

#ifdef LOG_PACKETS
log_packet(p); /* group A */
#endif
#if LOG_PACKETS
log_packet(p); /* group B */
#endif

Three versions of config.h give three different programs.

config.h contains group A (#ifdef) group B (#if)
#define LOG_PACKETS 1 compiled compiled
#define LOG_PACKETS 0 compiled deleted
no definition deleted deleted

The middle row is the trap. Group B obeys the author’s 0. Group A does not: #ifdef asks only whether the name is defined, and it is, so the image logs every packet. In the last row, #if LOG_PACKETS raises no error: the preprocessor replaces the unknown name by 0 and silently deletes group B. GCC and Clang warn about such a name only when the option -Wundef is given. A fourth version, #define LOG_PACKETS with no value, makes #ifdef true and makes #if LOG_PACKETS an error, because the condition expands to nothing.

A reviewer who reads group B, sees that it is switched off, and concludes “no logging” is wrong about the image built with the header of row 2: that image contains group A and logs every packet. Rerunning that build’s compile command with -E settles the question, because its output contains the call from group A and not the call from group B.

Stated precisely

Section 6.10.1 of the C standard, titled conditional inclusion, states the rules. The condition of #if and #elif is an integer constant expression. Before it is evaluated, macros in it are expanded, except a name that is the operand of defined; each defined NN or defined(NN) becomes 1 if NN is defined as a macro at that line and 0 otherwise; and every identifier still left becomes 0. The arithmetic uses the widest integer types, intmax_t and uintmax_t. #ifdef NN means the same as #if defined NN, and #ifndef NN the same as #if !defined NN. In one chain, only the first group whose condition is nonzero is processed, or the #else group if no condition is nonzero. The other groups are skipped, and in a skipped group only the names of directives are examined, to keep track of nesting.

For a macro name NN at a given line, two facts are separate. Presence: NN is defined or not, which #ifdef tests. Value: the integer that NN expands to, with an undefined name counting as 0, which #if tests. “Defined as 0” is present with value 0.

The groups compiled for one translation unit, the C standard’s name for one source file together with everything it includes, are determined by four inputs: the text of the source file and of every header it reads; the definitions and include directories on the command line; which file each #include finds along the include path; and the compiler’s predefined macros. Two compilations that agree on all four compile the same groups. A difference in any of them can change the groups, with no change to the source file.

Limits and common mistakes

Conditional compilation is not a run-time branch. An ordinary C statement if (LOG_PACKETS) { ... } compiles both branches, checks both for errors, and leaves the optimizer to remove the branch that a constant condition makes dead. #if deletes the text before compilation, so a deleted group is never checked.

A misspelled name is silently false. #ifdef LOG_PACKET, without the final S, is false when only LOG_PACKETS is defined, and nothing warns.

A macro’s value can change within a translation unit. A later #define replaces an earlier one or a command-line definition (compilers warn when the new definition differs), and #undef removes it. Each test uses the definition in force at its own line, while -dM shows only the state at the end of preprocessing.

Compiled does not mean present in the image. The linker §12.4 can discard a compiled function that nothing calls, and the optimizer can remove code it proves unreachable. Present in the image does not mean executed.

Configuration systems follow their own conventions. Kconfig writes #define CONFIG_X 1 for an enabled yes-or-no option and writes nothing for a disabled one, so #ifdef and #if agree on such options. A hand-written header that defines 0 for “off” breaks that agreement, as in the example.

Testing one configuration tests only the groups it compiles. A defect in a group that no tested build includes is never compiled, let alone run. Projects with many options therefore build and test several combinations.

Questions answered

Which branch actually reached the compiler for a specific image?

The branch that reached the compiler is the group that the preprocessor kept when that image was built. The preprocessor is the stage that runs before compilation; it deletes every group of an #if or #ifdef chain whose condition is false under the macro definitions in force at that line. Only the record of that build can show which group it was; the source text cannot, because it contains every group. To establish it:

  1. recover the exact compile command for the file from that build, with its -D and -U definitions and its include directories;

  2. use the generated configuration headers from the same build, not from a later one;

  3. rerun the command with -E to print the preprocessed text, in which only the kept group appears, or with -E -dM to list the macro values at the end of preprocessing;

  4. confirm in the image, for example by a symbol or string that only one group produces.

While reading the conditions, keep presence and value apart: #ifdef X is true for #define X 0, while #if X is false for it, and #if X is also false, without any error, when X is not defined at all. A review of a group that the build deleted says nothing about the code in the image.

Related entries: Source closure (§13.6), Compiler flag (§12.3), Helper contract (§2.21), Compiler correctness (§3.40), Kconfig (§6.40), Firmware build profile (§6.44), Linker (§12.4), GCC and Clang (§12.17). Further reading: [78].