C Conditional Compilation – Preprocessor Directives
Conditional compilation in C allows the compiler to include or exclude parts of the code based on specified conditions. This is particularly useful for creating portable code that can adapt to different environments, configurations, or debugging needs.
๐น #if, #else, #elif, #endif
The preprocessor directives #if, #else, #elif, and #endif are used to conditionally compile code based on certain conditions or constants.
๐ Example 1: Using #if to Include Code Based on a Condition
The following code will print “Debugging Mode” if the DEBUG constant is defined.
#include <stdio.h>
#define DEBUG
int main() {
#if defined(DEBUG)
printf("Debugging Mode\n");
#else
printf("Production Mode\n");
#endif
return 0;
}
๐น #elif and #else
You can use #elif for multiple conditions or #else as the default case.
๐ Example 2: Using #elif and #else
This code will check if a specific operating system is defined and print a corresponding message.
#include <stdio.h>
#define LINUX
int main() {
#if defined(WINDOWS)
printf("Windows OS\n");
#elif defined(LINUX)
printf("Linux OS\n");
#else
printf("Unknown OS\n");
#endif
return 0;
}
๐น Nested Conditional Compilation
You can also nest conditional compilation directives inside each other.
๐ Example 3: Nested #if
#include <stdio.h>
#define FEATURE_X
int main() {
#if defined(FEATURE_X)
#if defined(DEBUG)
printf("Feature X in Debug Mode\n");
#else
printf("Feature X in Production Mode\n");
#endif
#endif
return 0;
}
โ๏ธ Common Use Cases
- Enabling or disabling code based on platform or environment (e.g., Windows, Linux).
- Including debugging or logging code only in certain builds.
- Creating cross-platform programs by using conditional compilation for platform-specific code.
๐ฏ Recap
Conditional compilation is a powerful feature in C that allows you to control which parts of the code are compiled based on conditions defined during preprocessing. It is often used for debugging, cross-platform compatibility, and managing feature sets.