预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理,指令以 # 开头,不需要以分号;结尾。
预处理器主要是完成文本替换的操作
常见的预处理器
预处理器 | 描述 |
---|---|
#include | 导入头文件 |
#if | if判断操作,必须有#endif配对使用 |
#elif | 类似于 else if |
#else | else |
#endif | 结束if |
#define | 定义一个宏 |
#ifdef | 如果已经定义了一个宏 |
#ifndef | 如果还没有定义一个宏 |
#undef | 取消定义宏 |
#pragma | 设定编译器的状态 |
#define 宏变量
用于创建符号常量,称为宏。
#include <iostream>
#define NUMBER1 30
#define NUMBER2 "hello"
#define NUMBER3 30.222
int main() {
int a = NUMBER1; // 在实际编译之前,会被替换为 int a = 30;
std::string s = NUMBER2; // 在实际编译之前,会被替换为 std::string s = "hello";
float f = NUMBER3; // 在实际编译之前,会被替换为 float f = 30.222;
std::cout << a << std::endl;
std::cout << s << std::endl;
std::cout << f << std::endl;
return 0;
}
#ifndef、#define
如果没有定义宏NUMBER
就进行定义宏NUMBER为30
#include <iostream>
#ifndef NUMBER
#define NUMBER 30
#endif
int main() {
std::cout << NUMBER << std::endl;
return 0;
}
#ifdef
#include <iostream>
#ifndef NUMBER1
#define NUMBER1 30
#endif
int main() {
#ifdef NUMBER
std::cout << NUMBER << std::endl;
#else
std::cout << "not define NUMBER!" << std::endl;
#endif
return 0;
}
#if、#elif、#else、#endif
#include <iostream>
#ifndef NUMBER
#define NUMBER 30
#endif
int main() {
#if NUMBER <= 50
std::cout << " <= 50" << std::endl;
#elif NUMBER <= 100
std::cout << " <= 100" << std::endl;
#else
std::cout << " > 100" << std::endl;
#endif
return 0;
}
#undef
#include <iostream>
int main() {
#ifndef NUMBER
#define NUMBER 30
#endif
#ifdef NUMBER
std::cout << NUMBER << std::endl;
#else
std::cout << "not define NUMBER!" << std::endl;
#endif
#undef NUMBER
#ifdef NUMBER
std::cout << NUMBER << std::endl;
#else
std::cout << "not define NUMBER!" << std::endl;
#endif
return 0;
}
// 结果:
// 30
// not define NUMBER!
宏函数
优点:文本替换,不会造成函数的调用开销(开辟栈空间,形参压栈,函数弹栈释放等)
缺点:会导致代码体积增加
#include <iostream>
#define TEST1(a) std::cout << a << std::endl;
#define TEST2(a, b) a + b
#define TEST3(a, b) a * b
int main() {
TEST1(100); // 100
int res = TEST2(1+1, 2+2);
std::cout << res << std::endl; // 6
int res2 = TEST3(1+1, 2+2);
std::cout << res2 << std::endl; // 5
// int res2 = TEST3(1+1, 2+2);
// 被替换为:
// int res2 = 1 + 1 * 2 + 2; 替换后,乘法优先了
return 0;
}
预定义宏
#include <iostream>
int main() {
std::cout << __DATE__ << std::endl; // Sep 24 2021
std::cout << __TIME__ << std::endl; // 08:47:59
std::cout << __TIMESTAMP__ << std::endl; // Fri Sep 24 08:47:54 2021
return 0;
}