Conditional compilation allows to conditional define what instructions can be compiled and what to skip. We achieve this using conditional directives such as #ifdef, #ifndef, #endif etc.

#ifdef checks whether an identifier is defined using #define directive or not and conditionally includes or skips the instructions. For example consider the follow code.

#define DO_ADD
 
int main()
{
    int a{1}, b{3};
 
#ifdef DO_ADD
    int result{a + b};
#endif
 
    return 0;
}
 

When we preprocess it, we should have addition in the preprocessed output.

clang++ -ggdb -std=c++20 -E conditionals.cpp -o conditionals.i

When we open conditionals.i file,

# 1 "conditional_directives.cpp"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 518 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "conditional_directives.cpp" 2
 
 
int main()
{
    int a{1}, b{3};
    int result{a + b};
    return 0;
}
 

we have the addition. However, if we do not define the identifier and run the command again, we will not have the addition.

Note

  • Macros defined using #define are not substituted when used within another directive, conditional directive in this case.

References

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-the-preprocessor/#:~:text=acceptable%20to%20use.-,Conditional%20compilation,-The%20conditional%20compilation