Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Fundamentals of Conditional Compilation | Conditional compilation
C Preprocessing
course content

Cursusinhoud

C Preprocessing

C Preprocessing

1. Introduction to Preprocessing
2. Macros
3. Conditional compilation

book
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).

c

main

copy
12345678910
#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.

c

main

copy
123456789101112131415
#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.

question mark

What is the purpose of conditional compilation in C?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 1
Onze excuses dat er iets mis is gegaan. Wat is er gebeurd?
some-alt