Topics / C Programming / Q39
What is conditional compilation, and how is it used in embedded projects?
Short answer: Conditional compilation uses preprocessor directives (#if, #ifdef, #ifndef, #elif, #else, #endif, and the defined() operator) to include or exclude code before it is compiled. Embedded projects use it to build one code base for several boards and MCUs, to enable debug features, and to select features at build time.
#if defined(BOARD_REV_B)
# define LED_PIN 5
#elif defined(BOARD_REV_A)
# define LED_PIN 3
#else
# error "Unknown board revision"
#endif
#ifndef UART_BAUD
# define UART_BAUD 115200u /* default that can be overridden with -DUART_BAUD=9600 */
#endif
#if DEBUG_LEVEL >= 2
# define LOG_DEBUG(...) log_msg(__VA_ARGS__)
#else
# define LOG_DEBUG(...) do { } while (0) /* compiled out completely */
#endif
Where the symbols come from: -D options on the compiler command line (set by Make/CMake per build configuration), a generated config.h (Kconfig in Zephyr and Linux, sdkconfig.h in ESP-IDF), and compiler-predefined macros (__ARM_ARCH, __GNUC__, __BYTE_ORDER__, __ARM_FEATURE_DSP).
#ifdef vs #if
#ifdef Xchecks only whetherXis defined, even if it is defined as 0.#if Xevaluates its value; an undefinedXsilently counts as 0. GCC's-Wundefwarns about that, which catches typos like#if DEBUG_LEVLE > 1.- Kconfig-style systems prefer
#if IS_ENABLED(CONFIG_FOO)orif (IS_ENABLED(CONFIG_FOO))in C code, so both branches are still compiled and type-checked.
Good practice
- Use
#errorto stop the build when a required option is missing or inconsistent. - Keep
#ifdefblocks small; large conditional regions make code hard to read and test. Prefer separate source files per platform, selected by the build system (uart_stm32.c,uart_nrf.c). - Remember that code inside a disabled
#ifis not compiled at all, so it can rot. CI should build all configurations.