#ifdef
#ifdef
教程C++ 的 #ifdef
用于判断,如果一个标识符已被 #define
命令定义过,那么就编译该段代码,否则不编译。同时,#ifdef
还可以配合 #else
一起使用。
#ifdef
详解#ifdef identity
code1
#endif
如果标识符 identity 被定义过了,那么就编译代码 code1,否则就不编译。
#ifdef identity
code1
#else
code2
#endif
#ifdef
也可以配合 #else
一起使用,这里说明,如果标识符 identity 被定义过了,那么就编译代码 code1,否则就编译代码 code2。
#ifdef
使用 #ifdef
条件编译,执行编译代码
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
#ifdef PRINT
cout << "Print has defined" << endl;
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
我们首先使用了 #ifdef
来判断宏 PRINT 是否已经定义,如果已经定义了,则执行 cout 对应的代码,因为,我们的代码没有定义该宏,所以 cout 代码未被执行。现在,我们修改程序如下:
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
#define PRINT
#ifdef PRINT
cout << "Print has defined" << endl;
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
这次,我们使用了 #define
定义了 PRINT 宏,此时,再次执行该程序,程序执行了 cout 代码。
#ifdef
使用 #ifdef
和 #else
执行不同的编译代码
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
#ifdef PRINT
cout << "Print has defined" << endl;
#else
cout << "Print not defined" << endl;
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
我们首先使用了 #ifdef
来判断宏 PRINT 是否已经定义,如果已经定义了,则执行第一个 cout 对应的代码,如果没有定义,那么就执行第二个 cout 代码。
因为,我们的代码没有定义该宏,所以执行了第二个 cout 代码。现在,我们修改程序如下:
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
#define PRINT
#ifdef PRINT
cout << "Print has defined" << endl;
#else
cout << "Print not defined" << endl;
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
这次,我们使用了 #define
定义了 PRINT 宏,此时,再次执行该程序,程序执行了第一个 cout 代码。因此,我们使用了 #ifdef
和 #else
实现了控制不同的代码编译逻辑。
#ifdef
教程总结C++ 的 #ifdef
用于判断,如果一个标识符已被 #define
命令定义过,那么就编译该段代码,否则不编译。同时,#ifdef
还可以配合 #else
一起使用。