C语言编译预处理3
条件编译:是对源程序的一部分指定编译条件,满足条件进行编译否则不编译。
形式1
#indef 标识符
程序段1
#else
程序段2
#endif
标识符已经被定义用#ifdef
#include <stdio.h>
// 可以通过注释或取消注释下面这行来控制是否定义 DEBUG 宏
// #define DEBUG 定义标识符的操作
#ifdef DEBUG
// 如果已经定义 DEBUG 宏,执行此程序段
#define MESSAGE "当前处于发布版本,无调试信息。"
#else
// 如果未定义了 DEBUG 宏,执行此程序段
#define MESSAGE "当前处于调试版本,可输出详细信息。"
#endif
int main() {
printf("%s\n", MESSAGE);
return 0;
}
形式2
#ifndef 标识符
程序段1
#else
程序段2
#endif
标识符未被定义用#indef
#include <stdio.h>
// 可以通过注释或取消注释下面这行来控制是否定义 DEBUG 宏
// #define DEBUG
#ifndef DEBUG
// 如果未定义 DEBUG 宏,执行此程序段
#define MESSAGE "当前处于发布版本,无调试信息。"
#else
// 如果定义了 DEBUG 宏,执行此程序段
#define MESSAGE "当前处于调试版本,可输出详细信息。"
#endif
int main() {
printf("%s\n", MESSAGE);
return 0;
}
//针对标识符DEBUG是否被定义,得到MESSAGE的值
形式3
#if 常量表达式
程序段1
#else
程序段2
#endif
如上所得若常量表达式为真执行程序1,否则执行程序2。
#include <stdio.h>
// 定义常量表达式的值
#define VERSION 2 //常量表达式被定义
#if VERSION == 1
// 当 VERSION 等于 1 时,编译此程序段
#define MESSAGE "这是版本 1 的程序。"
#elif VERSION == 2
// 当 VERSION 等于 2 时,编译此程序段
#define MESSAGE "这是版本 2 的程序。"
#else
// 当 VERSION 既不等于 1 也不等于 2 时,编译此程序段
#define MESSAGE "未知版本的程序。"
#endif
int main() {
printf("%s\n", MESSAGE);
return 0;
}
该程序输出 "这是版本 2 的程序。"