# 與 連接 ###define WARN_IF(EXP) if(EXP) cerr << #EXP << endl; // #EXP → "EXP"
#define PASTER(n) cout << "token" #n " = " << n << endl;
#define CONCAT(a, b) a##b // 連接標識符
WARN_IF(div == 0); // 輸出: div == 0
PASTER(9); // 輸出: token9 = 9
cout << CONCAT(1, 2) << endl; // 輸出: 12 (注意:非 3!)
注意:帶 #/## 的宏參數不再遞歸展開。需兩層宏強制展開:
#define STR(s) #s
#define XSTR(s) STR(s)
#define VAL 42
cout << XSTR(VAL) << endl; // 輸出: 42 (非 "VAL")
#include 搜索路徑差異| 語法 | 搜索順序 | 適用場景 |
|---|---|---|
<header> | 系統目錄 → 環境變量路徑 | 標準庫、系統頭文件 |
"header" | 當前目錄 → 系統目錄 → 環境變量 | 項目內部頭文件 |
推薦包含順序(Google 風格):相關頭文件 → C 系統 → C++ 系統 → 第三方庫 → 本項目內部。
#if #elif #else #endif#if DEBUG_LEVEL > 1
log_detail();
#elif DEBUG_LEVEL == 1
log_base();
#else
// release
#endif
條件必須為整型常量表達式,可用 defined(MACRO) 判斷宏是否定義。
#define #undef #ifdef #ifndef#define PI 3.14159
#define ADD(x,y) ((x)+(y))
#ifdef DEBUG
cout << "Debug: " << x << endl;
#endif
#ifndef GUARD_H
#define GUARD_H
// 頭文件內容
#endif
現代 C++ 亦可用 #pragma once 防重複包含(編譯器支持廣泛)。
#line 修改行號/文件名#line 100 "custom.cpp"
cout << __LINE__ << " " << __FILE__; // 輸出: 100 custom.cpp
常用於代碼生成工具輸出映射原始源碼位置。
#error 強制編譯錯誤#ifndef VERSION
#error "版本號未定義!"
#endif
編譯器直接報錯並停止,用於強制配置檢查。
#define LOG(msg) cerr << __FILE__ << ":" << __LINE__ << " " << #msg << "=" << (msg) << endl;#define STATIC_ASSERT(cond) typedef char static_assert_failed[(cond)?1:-1] (C++11 前)#ifdef _WIN32 ... #elif __linux__ ... #endif