跨平台、多配置構建時,源碼需根據宏定義選擇性編譯不同代碼路徑,避免維護多份副本。標準庫(如 STL)大量使用此技術適配編譯器/平台差異。
#ifndef / #define / #endif
// json_autolink.h
#ifndef JSON_AUTOLINK_H_INCLUDED
#define JSON_AUTOLINK_H_INCLUDED
// ... 類/函數聲明 ...
#endif // JSON_AUTOLINK_H_INCLUDED
#pragma once(編譯器擴展,非標準但廣泛支持)。#ifdef / #else / #endif
#ifdef JSON_VALUE_USE_INTERNAL_MAP
class ValueAllocator;
class ValueMapAllocator;
// ... 內部實現細節 ...
#endif
-DJSON_VALUE_USE_INTERNAL_MAP 或配置頭文件 #define JSON_VALUE_USE_INTERNAL_MAP 控制是否編譯該模塊。#if / #elif / #else / #endif 配合 defined()
#if defined(_PTHREADS) && !defined(_NOTHREADS)
#define __STL_PTHREADS
#endif
#if defined(_UITHREADS) && !defined(_PTHREADS) && !defined(_NOTHREADS)
#define __STL_UITHREADS
#endif
#if defined(__sgi) && !defined(__GNUC__)
#include
#if !defined(_BOOL)
#define __STL_NO_BOOL
#endif
#if defined(_MIPS_SIM) && _MIPS_SIM == _ABIO32
#define __STL_STATIC_CONST_INIT_BUG
#endif
#endif
defined(MACRO) 返回 1/0,可用於 #if 表達式中,比 #ifdef 更靈活(支持邏輯運算)。__GNUC__, _WIN32, __linux__ 等)實現平台適配。_COMPILER_VERSION >= 730)。#define 的雙重角色#define MAX 100, #define SQR(x) ((x)*(x))。建議改用 const/constexpr 和 inline 函數,擁有類型安全、作用域、調試可見性。#ifdef/#if defined() 的判斷依據,不產生代碼。MYLIB_USE_SSL),避免衝突。config.h,由構建系統生成或手動維護。#if,增加閱讀難度;必要時拆分為獨立源文件。條件編譯是 C/C++ 靜態多態的基石,善用之可構建高可移植、可配置的代碼庫。