条件付きコンパイル
#ifdef でデバッグ、プラットフォーム、機能を切り替え。
#ifdef
定義されていれば有効。
#if
式が真なら有効。
#error
コンパイルを中止。
条件付きコンパイル
// 条件付きコンパイル
// デバッグ用コード#ifdef DEBUG printf("Debug: x = %d\n", x);#endif
// コンパイル時: gcc -DDEBUG main.c
// 機能の有効/無効#ifndef FEATURE_X #define FEATURE_X 1#endif
#if FEATURE_X // Feature X のコード#endif
// プラットフォーム判定#if defined(_WIN32) #include <windows.h>#elif defined(__linux__) #include <unistd.h>#elif defined(__APPLE__) #include <mach/mach.h>#endifBad
// ❌ Bad: 実行時に分岐if (debug_mode) { printf("Debug: x = %d", x);}// リリースでも不要なコードが残るGood
// ✅ Good: コンパイル時に分岐#ifdef DEBUG printf("Debug: x = %d", x);#endif// リリースでは完全に削除されるパターン
// バージョン判定#if __STDC_VERSION__ >= 201112L // C11 以降#endif
// コンパイラ判定#if defined(__GNUC__) // GCC/Clang#elif defined(_MSC_VER) // Visual Studio#endif
// 機能テスト#if __has_attribute(always_inline) #define FORCE_INLINE __attribute__((always_inline))#else #define FORCE_INLINE inline#endif
// #error でコンパイルを止める#if !defined(CONFIG_VALUE) #error "CONFIG_VALUE must be defined"#endif
// #warning で警告#warning "This feature is deprecated"
// #elif, #else#if MODE == 1 // モード1#elif MODE == 2 // モード2#else // デフォルト#endif Tip: -DDEBUG でデバッグビルド。
合格ライン
#ifdef でデバッグ分岐できる
プラットフォーム判定ができる