阅读耗时大概 1 分钟

define 预处理

#define macro-name replacement-text
我们常说的宏常量不就是这样写的么。 在程序编译前 会将 macro-name 替换成 我们定义的值
直接看代码吧

  1. #include <iostream>
  2. using namespace std;
  3. #define PI 3.14159
  4. int main ()
  5. {
  6. cout << "Value of PI :" << PI << endl;
  7. return 0;
  8. }
  9. 输出结果是
  10. Value of PI :3.14159

参数宏

  1. #include <iostream>
  2. using namespace std;
  3. #define MIN(a,b) (a<b ? a : b)
  4. int main ()
  5. {
  6. int i, j;
  7. i = 60;
  8. j = 30;
  9. cout <<"较小的值为:" << MIN(i, j) << endl;
  10. return 0;
  11. }
  12. 输出结果
  13. 较小的值为: 30

条件编译

主要是利用几个指令来有选择地对部分程序源代码进行编译。和 if else 逻辑很像
只在调试时进行编译,调试开关可以使用一个宏来实现

  1. //如果之前定义了符号常量debug
  2. #ifdef DEBUG
  3. cerr <<"Variable x = " << x << endl;
  4. #endif

注释代码

  1. #if 0
  2. //不进行编译的代码
  3. #endif
  1. #include <iostream>
  2. using namespace std;
  3. #define DEBUG
  4. #define MIN(a,b) (((a)<(b)) ? a : b)
  5. int main ()
  6. {
  7. int i, j;
  8. i = 100;
  9. j = 30;
  10. #ifdef DEBUG
  11. cerr <<"Trace: Inside main function" << endl;
  12. #endif
  13. #if 0
  14. /* 这是注释部分 */
  15. cout << MKSTR(HELLO C++) << endl;
  16. #endif
  17. cout <<"The minimum is " << MIN(i, j) << endl;
  18. #ifdef DEBUG
  19. cerr <<"Trace: Coming out of main function" << endl;
  20. #endif
  21. return 0;
  22. }
  23. 输出结果
  24. Trace: Inside main function
  25. The minimum is 30
  26. Trace: Coming out of main function

#和##运算符

  1. #include <iostream>
  2. using namespace std;
  3. #define MKSTR( x ) #x
  4. int main ()
  5. {
  6. //下面这句话 直接经过预处理器 转换成了 HELL C++
  7. cout << MKSTR(HELLO C++) << endl;
  8. return 0;
  9. }
  10. 输出结果
  11. HELLO C++

##运算符用于连接两个参数令牌
#define CONCAT( x, y ) x ## y

  1. #include <iostream>
  2. using namespace std;
  3. #define concat(a, b) a ## b
  4. int main()
  5. {
  6. int xy = 100;
  7. //编译器预处理后变成了 xy
  8. cout << concat(x, y);
  9. return 0;
  10. }
  11. 输出结果
  12. 100

预定义宏

描述
LINE 会在程序编译时包含当前行号
FILE 会在程序编译时包含当前文件名
DATE 会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期
TIME 会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间
  1. #include <iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5. cout << "Value of __LINE__ : " << __LINE__ << endl;
  6. cout << "Value of __FILE__ : " << __FILE__ << endl;
  7. cout << "Value of __DATE__ : " << __DATE__ << endl;
  8. cout << "Value of __TIME__ : " << __TIME__ << endl;
  9. return 0;
  10. }
  11. 输出结果
  12. Value of __LINE__ : 6
  13. Value of __FILE__ : test_define.cpp
  14. Value of __DATE__ : May 4 2022
  15. Value of __TIME__ : 20:01:19