C++预处理器指令详解:#define宏、条件编译、#/#运算符与预定义宏
预处理器指令指导编译器在正式编译前预处理源码。所有指令以#开头,行首仅允许空白字符。指令非C++语句,**不以分号结尾**。
常见指令:#include、#define、#if、#else、#line等。
#define预处理器
创建符号常量(宏)。通用形式:
#define macro-name replacement-text
后续出现macro-name均被replacement-text文本替换。示例:
#include <iostream>
using namespace std;
#define PI 3.14159
int main() { cout << "Value of PI :" << PI << endl; return 0; }
预处理后(gcc -E)主函数变为:
int main() { cout << "Value of PI :" << 3.14159 << endl; return 0; }
函数式宏
#define可带参数:
#include <iostream>
using namespace std;
#define MIN(a,b) (((a)<(b)) ? a : b)
int main() {
int i=100, j=30;
cout << "The minimum is " << MIN(i, j) << endl; // 30
return 0;
}
注意参数加括号防优先级错误。
条件编译
选择性编译源码部分。类似if结构:
#ifndef NULL
#define NULL 0
#endif
调试开关示例:
#ifdef DEBUG
cerr << "Variable x = " << x << endl;
#endif
仅当DEBUG已定义时编译cerr语句。用#if 0 ... #endif注释大段代码:
#if 0
被阻止编译的代码
#endif
综合演示:
#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main() {
int i=100, j=30;
#ifdef DEBUG
cerr << "Trace: Inside main function" << endl;
#endif
#if 0
cout << MKSTR(HELLO C++) << endl; // 被注释
#endif
cout << "The minimum is " << MIN(i, j) << endl;
#ifdef DEBUG
cerr << "Trace: Coming out of main function" << endl;
#endif
return 0;
}
输出:The minimum is 30及两行Trace日志。
#与##预处理运算符
#(字符串化):将替换文本标记转为带引号字符串。#define MKSTR(x) #x→MKSTR(HELLO C++)展开为"HELLO C++"。##(标记粘贴):连接两个标记。#define CONCAT(x,y) x##y→CONCAT(HELLO, C++)生成HELLOC++。示例:concat(x,y)与变量xy结合输出100。
预定义宏
| 序号 | 宏与说明 |
|---|---|
| 1 | __LINE__ 编译时当前行号。 |
| 2 | __FILE__ 编译时当前文件名。 |
| 3 | __DATE__ 编译日期,格式 |
| 4 | __TIME__ 编译时间,格式 |
演示:
#include <iostream>
using namespace std;
int main() {
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
输出示例:__LINE__:6、__FILE__:test.cpp、__DATE__:Feb 28 2011、__TIME__:18:52:48。
C语言
- 掌握 C# 预处理器指令:条件编译、诊断控制与代码组织实战
- 深入理解 C++ 数据类型:基础类型、修饰符与最佳实践
- 掌握 C++ 运算符:六大类型全解析与实战示例
- C++ 注释最佳实践:编写可读、可维护代码的注释艺术
- C++构造函数详解:默认、参数化与拷贝构造函数
- C++ 类模板实战指南:编写灵活的类型无关代码
- 深入理解 C 预处理器 (CPP):它如何简化编译过程
- C++编程语言:核心特性全景解析
- C++常量与字面量完全手册:类型、语法与最佳实践
- C++运算符大全:算术/关系/逻辑/位/赋值/杂项与优先级结合性
- C++数值类型实战指南:基本类型、数学函数与随机数生成
- C++引用详解:核心概念、与指针三大差异及函数参数/返回值应用