Cursusinhoud
C Preprocessing
C Preprocessing
Fundamentals of Conditional Compilation
It does not affect the runtime behavior but determines what gets included in the final binary. This is useful for adapting code to different platforms, configurations, or versions. Typical use cases include:
- Debug builds: insert logs or debug information only during development.
- Platform-specific code: use
#ifdef _WIN32
for Windows,__linux__
for Linux, etc. - Feature toggling: enable or disable modules based on configuration settings.
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. You can also use multiple conditional branches, which is great for version control and managing different builds.
main
#include <stdio.h> // Choose 1, 2 or another value #define VERSION 2 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 works like a switch...case
or if()
statement, but the key difference is that branching happens before runtime. Unlike runtime checks, it lets you include or exclude large chunks of code, making the final program lighter.
You can think of conditional compilation like a set of electrical switches in your code. Each #if
, #ifdef
, or #ifndef
acts like a switch turning code on or off before the compiler even sees it.
Bedankt voor je feedback!