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

bookFundamentals 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.c

main.c

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.

main.c

main.c

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  1
some-alt