Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Feature flag and compile-time configuration

A compile-time flag selects a program variant when you build it. A runtime flag changes the behavior of an already-built program.

Version: ISO C++23; implementation support may vary

Syntax

#ifndef CKTIS_ENABLE_TRACE
#define CKTIS_ENABLE_TRACE 0
#endif

#if CKTIS_ENABLE_TRACE
// C++ declarations or statements included when the flag is 1.
#endif

// Alternative for selecting between C++ statements:
constexpr bool use_trace = CKTIS_ENABLE_TRACE != 0;
// Inside a function: if constexpr (use_trace) { /* ... */ }

The key distinction in feature flag and compile-time configuration is when the choice is made. A build-time flag selects what gets compiled, and changing it requires rebuilding the affected parts. A runtime setting, such as a value read from a config file, can control an ordinary if without recompilation. A flag is not a substitute for authorization checks.

Give CKTIS_ENABLE_TRACE a 0 or 1 contract and use #ifndef to default it to 0 when it is not defined. #if CKTIS_ENABLE_TRACE tests the value; #ifdef CKTIS_ENABLE_TRACE tests only whether the macro is defined, so even 0 passes. Skipped code is not parsed as C++. Use #if when an optional header or declaration must be left out.

To select between C++ statements, use a constexpr bool with if constexpr. The preprocessor cannot read a C++ variable in #if. Both branches of if constexpr are parsed, and outside a template the compiler checks the discarded branch too. When instantiating a template, the compiler does not instantiate the discarded branch once the condition is no longer value-dependent.

In ISO C++23, __cpp_* and __cpp_lib_* macros report language or library support, not whether your project chooses to use a feature. Support can vary by implementation. Before checking a library macro, include <version> or the relevant header and compare its value against the required revision. Keep flags that affect shared header definitions consistent across the translation units that use them: differing definitions of the same inline function can violate the one-definition rule (ODR). Build and test both variants.

Examples

#include <iostream>

#ifndef CKTIS_ENABLE_TRACE
#define CKTIS_ENABLE_TRACE 0
#endif

#if CKTIS_ENABLE_TRACE
void trace_startup() {
    std::cout << "trace: enabled\n";
}
#endif

int main() {
#if CKTIS_ENABLE_TRACE
    trace_startup();
#endif
    std::cout << "ready\n";
}

Result

ready

By default, the program prints only `ready`. Rebuild with `CKTIS_ENABLE_TRACE=1` to print `trace: enabled` on the line before `ready`. With `0`, preprocessing leaves out both the definition of `trace_startup` and its call.

Related lessons

  • C++ · Lesson 60 · Advanced · Version: 3

Sources