Зміст курсу
C Preprocessing
C Preprocessing
Fundamentals of Conditional Compilation
It does not affect the runtime behavior but determines what gets into the final binary.
This is useful for adapting code for different platforms, configurations, or versions.
Tipical use cases include:
-
Debug builds
: iIserting logs only during development; -
Platform-specific code
: Use#ifdef _WIN32
for Windows,__linux__
for linux; -
Feature toggling
: Enabling or disabling modules based on cofiguration (e.g., Bluetooth support).
The preprocessor evaluates conditions based on defined macros.
Expressions in #if
and #elif
are evaluated similarly to C expressions but with limited operators (arithmetic, logical, comparison).
main
#include <stdio.h> #define FEATURE_ENABLED int main() { #ifdef FEATURE_ENABLED printf("Feature is active!\n"); #endif return 0; }
This code prints the message only if FEATURE_ENABLED
is defined. If not, the line is completely removed before compilation.
Multiple conditional branches example:
main
#include <stdio.h> #define VERSION ___ // choose 1, 2 or another value int main() { #if VERSION == 1 printf("Old version\n"); #elif VERSION == 2 printf("Current version\n"); #else printf("Unknown version\n"); #endif return 0; }
This code is similar to a switch...case
statement or an if()
statement. However, the main difference is that the branching happens before the program actually starts running, because swithc...case
and if()
work at runtime.
Дякуємо за ваш відгук!