一、 预处理器
预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理。
所有的预处理器指令都是以井号(#)开头,只有空格字符可以出现在预处理指令之前。预处理指令不是 C++ 语句,所以它们不会以分号(;)结尾。
我们已经看到,之前所有的实例中都有 #include 指令。这个宏用于把头文件包含到源文件中。
C++ 还支持很多预处理指令,比如 #include、#define、#if、#else、#line 等,让我们一起看看这些重要指令。
二、宏
在编译之前,预先定义的宏(变量)
宏也可以理解为变量
#include <iostream>
using namespace std;
#define PI 3.14159
int main ()
{
cout << "Value of PI :" << PI << endl;
return 0;
}
三、条件编译
判断是否定义了这个宏
#ifdef 宏名称
//代码
#endif
#include <iostream>
//#define PI 3.14159
using namespace std;
int main ()
{
#ifdef PI
cout << "Value of PI :" << PI << endl;
#endif
cout << "Value of PI :" << 3 << endl;
return 0;
}
#include <iostream>
#define PI 3.14159
using namespace std;
int main ()
{
#ifdef PI
cout << "Value of PI :" << PI << endl;
#endif
cout << "Value of PI :" << 3 << endl;
return 0;
}
四、#与##
1.#
#include <iostream>
using namespace std;
#define MKSTR( x ) #x
int main ()
{
cout << MKSTR(HELLO C++) << endl;
return 0;
}
结果
HELLO C++
分析:
MKSTR( x ) 转换成了 x
所以MKSTR(HELLO C++) 转换成了 HELLO C++
2.##
#include <iostream>
using namespace std;
#define concat(a, b) a ## b
int main()
{
int xy = 100;
cout << concat(x, y);
return 0;
}
结果:
100
分析:
concat(a, b)转换成了 a ## b 即 concat(a, b)转换成了 ab
所以 concat(x, y)转换成了 xy
五、c++文件自带的宏(变量)
参考:Preprocessor directives - C++ Tutorials

484

被折叠的 条评论
为什么被折叠?



