Conditional Compilation
Conditional compilation uses preprocessor directives to keep or discard regions of source before the compiler sees them, so one codebase can produce different builds for different platforms or configurations.
Detailed Explanation
C runs on everything from a microcontroller to a supercomputer, and those targets do not offer the same facilities. There is no run-time way to write "use the Windows socket API here and the POSIX one there", because code referring to a header that does not exist on this machine will not even compile. The preprocessor solves it by deleting the text you do not want.
The directives form one family:
| Directive | Meaning |
|---|---|
#if expr | keep the region if the integer constant expression is non-zero |
#ifdef NAME | keep it if NAME is defined, regardless of its value |
#ifndef NAME | keep it if NAME is not defined |
#elif expr | otherwise, test another expression |
#else | otherwise |
#endif | end the region |
defined(NAME) is an operator you can use inside #if, and it is the more flexible choice: #if defined(__linux__) || defined(__APPLE__) has no #ifdef equivalent. #ifdef NAME is shorthand for #if defined(NAME).
The arithmetic inside #if is restricted and has two traps. It evaluates in the widest integer types the implementation supports, so results can differ from the same expression in C code. And any identifier left after macro expansion is replaced by 0. That means #if ENABLE_CACHE is false when you misspell the macro, when you forget to include the header that defines it, and when it is genuinely zero, with no way to tell them apart. Compile with -Wundef so the compiler tells you when this happens.
Three sources of macros drive these conditions.
- Compiler-provided target macros identify the platform:
__linux__,_WIN32,__APPLE__,__x86_64__,__ARM_ARCH. They are not standardised;cc -dM -E - < /dev/nulllists what your compiler defines. - Standard macros describe the language and library:
__STDC_VERSION__(199901Lfor C99,201112Lfor C11), and C11 opt-out macros such as__STDC_NO_ATOMICS__and__STDC_NO_THREADS__. - Your own configuration macros, set on the command line with
-DENABLE_CACHE=1or through a generatedconfig.h.-DNAMEwith no value defines it as1.
NDEBUG deserves a mention because it works backwards from most flags: assert is active by default and -DNDEBUG disables it, which is why release builds define it.
Now the honest cost. Conditional compilation is the least pleasant tool in C, for a reason that is easy to miss: the compiler only checks the branch it kept. The other branch is not parsed, not type checked, not warned about. It can contain a typo, a call to a function that was renamed six months ago, or a syntax error, and your build stays green until someone builds for that platform. Test coverage has the same hole. A file with eight independent #ifdefs has up to 256 possible texts, and continuous integration probably compiles two of them.
So push the conditionals to the edges. Rather than sprinkling #ifdef _WIN32 through twenty functions, define one small internal interface and write a separate implementation file per platform, selected by the build system. Where you must branch inline, prefer a form both branches compile: set a macro to 0 or 1 and use a normal if, which the optimizer removes and the compiler still checks. And always comment the #endif of a long region with the condition it closes.
Code Examples
/* platform.c — branching on the target, with both forms shown.
* cc platform.c -o platform -DENABLE_CACHE=1
* cc -dM -E - < /dev/null list every predefined macro
*/
#include <stdio.h>
/* defined() lets one condition cover several platforms. */
#if defined(__linux__) || defined(__APPLE__)
# include <unistd.h> /* POSIX: sleep() lives here */
# define PLATFORM_NAME "posix"
#elif defined(_WIN32)
# define PLATFORM_NAME "windows"
#else
# error "unsupported platform: add a branch for this target"
#endif
/* Give the option a default so #if never tests an undefined name.
With -Wundef the compiler warns if you misspell it anyway. */
#ifndef ENABLE_CACHE
# define ENABLE_CACHE 0
#endif
int main(void)
{
printf("built for %s\n", PLATFORM_NAME);
#if __STDC_VERSION__ >= 201112L
printf("C11 or later\n");
#else
printf("pre-C11\n");
#endif
/* A normal if, not an #if: both sides are always compiled and checked,
and the optimizer deletes the dead one because the test is constant. */
if (ENABLE_CACHE)
printf("cache enabled\n");
else
printf("cache disabled\n");
return 0;
}/* Keeping the conditionals at the edge instead of through the logic.
* The caller below contains no #ifdef at all, so it compiles once
* and is checked once, on every platform. */
#include <stdio.h>
#if defined(_WIN32)
# include <windows.h>
static void sleep_ms(unsigned ms) { Sleep(ms); }
#else
# include <time.h>
static void sleep_ms(unsigned ms)
{
struct timespec ts;
ts.tv_sec = ms / 1000u;
ts.tv_nsec = (long)(ms % 1000u) * 1000000L; /* nanoseconds */
nanosleep(&ts, NULL); /* POSIX, needs C99 + _POSIX_C_SOURCE */
}
#endif
int main(void)
{
printf("waiting\n");
sleep_ms(50); /* platform-independent from here down */
printf("done\n");
return 0;
}Common Gotchas
The discarded branch is never compiled, so its bugs are invisible
a syntax error or a stale function name in a `#else` region breaks the build only for whoever targets that platform, possibly months later. Build every supported configuration in CI, or restructure so both branches are always compiled.
An undefined macro in `#if` silently evaluates to zero
misspelling `ENABLE_CACHE` as `ENABLE_CACHHE` quietly selects the `#else` path. Enable `-Wundef`, give every option a default with `#ifndef`, and use `#if defined(X)` when you mean "is it set at all".
`#ifdef` tests presence, not truth
`-DENABLE_CACHE=0` makes `#ifdef ENABLE_CACHE` true. Pick one convention per option, either presence-based or value-based, and stay with it.
Deeply nested conditionals are unreadable without help
indent the `#` directives after the hash (`# include`, which is valid) and repeat the condition in a comment on the `#endif`. When a file has more than two or three independent conditions, splitting it per platform is usually cheaper than maintaining it.