C++ 预处理器
系统梳理 C++ 编译前预处理机制:#define 对象宏与参数宏、#ifdef/#if 0 条件编译、# 字符串化与 ## 记号拼接运算符,以及四大标准预定义宏。
学完这一章,你能够
- 系统梳理 C++ 编译前预处理机制:#define 对象宏与参数宏、#ifdef/#if 0 条件编译、# 字符串化与 ## 记号拼接运算符,以及四大标准预定义宏。
预处理阶段、#define 对象宏与参数宏
预处理器在实际词法与语法编译之前对源码执行文本级变换。所有预处理指令均以 `#` 开头(前面仅允许空白字符),它们不是 C++ 语句因此末尾不加分号;常见指令包括 `#include`、`#define`、`#ifdef`、`#if`、`#else`、`#endif` 与 `#line` 等。
`#define 宏名 替换文本` 用于定义符号宏,可用 `g++ -E` 观察预处理展开后的纯文本结果(如 `PI` 展开为 `3.14159`)。`#define` 还支持带参宏,例如 `#define MIN(a, b) (((a) < (b)) ? (a) : (b))`;编写参数宏必须对每个形参和整体加括号防止运算符优先级出错,且需留意实参可能被多次求值的副作用(现代 C++ 推荐优先用 `constexpr` 与内联函数模板替代)。
条件编译与 # / ## 预处理运算符
条件编译指令(`#ifdef`、`#ifndef`、`#if`、`#elif`、`#else`、`#endif`)可在编译前有选择地保留或剔除代码片段——典型用途包括头文件防重复包含守卫、借助 `#ifdef DEBUG` 开关调试日志,以及用 `#if 0 ... #endif` 临时屏蔽含嵌套 `/* */` 注释的大段代码。
预处理专有运算符 `#`(字符串化)会将宏实参记号直接转为带双引号的字符串字面量(如 `MKSTR(HELLO C++)` 展开为 `"HELLO C++"`);`##`(记号拼接)则将两个记号无缝合并为新标识符(如 `concat(x, y)` 展开为变量名 `xy`,注意拼接结果须构成合法 C++ 记号,不能拼出非法复合标点)。
标准预定义宏速查
ISO C++ 规定了若干内置预定义宏,在编译期自动展开为当前源码位置与构建时间信息(详见下表),广泛用于断言报错与日志追踪;此外 `__cplusplus` 宏会展开为当前启用的标准年份编码(如 C++17 为 `201703L`)。
C++ 常用标准预定义宏
| 宏名称 | 编译期展开含义 |
|---|---|
| __LINE__ | 展开为当前源代码行号对应的整型常量。 |
| __FILE__ | 展开为当前源文件名(或路径)的字符串字面量。 |
| __DATE__ | 展开为编译日期字符串(固定 11 字符 "Mmm dd yyyy" 格式)。 |
| __TIME__ | 展开为编译时间字符串(固定 8 字符 "hh:mm:ss" 24 小时制格式)。 |
验证对象宏/参数宏、条件编译分支、# 与 ## 展开及 __LINE__/__FILE__/__DATE__/__TIME__
#include <cstring>
#include <iostream>
#include <string>
#define PI_APPROX 3.14159
#define MIN_VAL(a, b) (((a) < (b)) ? (a) : (b))
#define DEBUG_MODE
#define MKSTR(x) #x
#define CONCAT(a, b) a ## b
int main() {
// 1. Object-like and function-like macros
int pi_scaled = static_cast<int>(PI_APPROX * 100000 + 0.5);
int m1 = MIN_VAL(100, 30);
int m2 = MIN_VAL(2 + 3, 4);
std::string act1 = std::to_string(pi_scaled) + ":" + std::to_string(m1) + ":" + std::to_string(m2);
const std::string exp1 = "314159:30:4";
bool ok1 = (act1 == exp1);
// 2. Conditional compilation (#ifdef, #ifndef, #if 0)
std::string trace;
#ifdef DEBUG_MODE
trace += "debug_on";
#endif
#ifndef RELEASE_MODE
trace += "|release_off";
#endif
#if 0
trace += "|unreachable";
#endif
const std::string exp2 = "debug_on|release_off";
bool ok2 = (trace == exp2);
// 3. Stringizing (#) and token-pasting (##) operators
std::string s_macro = MKSTR(HELLO C++);
int xy = 100;
int pasted = CONCAT(x, y);
std::string act3 = s_macro + ":" + std::to_string(pasted);
const std::string exp3 = "HELLO C++:100";
bool ok3 = (act3 == exp3);
// 4. Predefined macros (__LINE__, __FILE__, __DATE__, __TIME__, __cplusplus)
int cur_line = __LINE__;
std::string cur_file = __FILE__;
std::string cur_date = __DATE__;
std::string cur_time = __TIME__;
bool file_ends_ok = cur_file.size() >= 28 &&
cur_file.substr(cur_file.size() - 28) == "explore-cpp-preprocessor.cpp";
bool date_ok = (cur_date.size() == 11);
bool time_ok = (cur_time.size() == 8 && cur_time[2] == ':' && cur_time[5] == ':');
bool std_ok = (__cplusplus >= 201703L);
bool ok4 = (cur_line > 30) && file_ends_ok && date_ok && time_ok && std_ok;
std::cout << "{\n"
<< " \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
<< " \"cases\": [\n"
<< " {\"name\": \"object_and_function_macros\", \"expected\": \"" << exp1
<< "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
<< " {\"name\": \"conditional_compilation_branches\", \"expected\": \"" << exp2
<< "\", \"actual\": \"" << trace << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
<< " {\"name\": \"stringize_and_token_paste\", \"expected\": \"" << exp3
<< "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
<< " {\"name\": \"predefined_macros_contract\", \"expected\": true, \"actual\": "
<< (ok4 ? "true" : "false") << ", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
<< " ]\n"
<< "}\n";
return 0;
}
- 在 G++ 13.3.0 C++17 离线容器中验证 PI/MIN 宏展开、#ifdef/#ifndef/#if 0 分支裁剪、MKSTR 与 CONCAT 拼接以及四大预定义宏与 __cplusplus>=201703L 4 项全通过。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:56afd7a990ed2b27095da2603ce74b1b2778fc7b7c4bf197ca72bc751b25bc23
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:c6496e4cac63d4163c5bca312d1098ca623cd3de5f2ffb00b76e6e5e88a985c5
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么参数宏 `#define MIN(a, b) (a < b ? a : b)` 在传入 `MIN(x++, y)` 时会产生隐患?现代 C++ 推荐用什么替代?
展开参考解答
因为宏只是纯文本替换,`MIN(x++, y)` 会展开成 `(x++ < y ? x++ : y)`,导致 `x++` 被求值两次(且缺少括号时易受外部运算符优先级影响);现代 C++ 应优先使用 `std::min` 或内联函数模板。