条件编译就是宏定义加上预处理的应用,作用在于同一份代码产生不同的产品
1、基本概念
— 条件编译的行为类似于C语言的 if…else…
— 条件编译是预编译指示命令,用于控制是否编译某段代码
#include <stdio.h>
#define C 1
int main()
{
const char* s;
#if(C == 1)
s = "This is first printf...\n";
#else
s = "This is second printf...\n";
#endif
printf("%s\n", s);
return 0;
}
#if 、#else用来指示我们的预处理器,保留什么代码,删除什么代码,所以到了编译阶段,我们不想要的代码其实就已经被预处理器给删除了。
2、条件编译的本质
— 预编译期根据条件编译指令有选择的删除代码
— 编译器不知道代码分支的存在(预处理器执行的)
— if…else…语句在运行期进行分支判断
— 条件编译指令在预编译期进行分支判断
— 可以通过命令行定义宏
3、#include 的本质
— #include 的本质是将已经存在的文件内容嵌入到当前文件中
— #include 的间接包含同样会产生嵌入文件内容的操作
问题:间接包含同一个头文件是否会产生编译错误?
回答:容易造成在一个程序中重复定义的错误,所以条件编译可以避免这种情况
所以一般在头文件里面,我们都要这样写
#ifndef _HEADER_FILE_H
#define _HEADER_FILE_H
...//source code
#endif
4、条件编译的意义
— 条件编译使得我们可以按照不同的条件编译不同的代码段,因而可以产生不同的目标代码
— #if…#else…#endif 被预编译期处理,而if…else语句被编译器处理,必然被编译进目标代码(#if等同于if)
— 实际工程中条件编译主要用于以下两种情况:
—— 不同的产品线共用一份代码
—— 区分编译产品的调试版和发布版
//product.h
#define DEBUG 1
#define HIGH 1
//1.c
#include <stdio.h>
#include "product.h"
#if DEBUG
#define Log(s) printf("[%s:%d] %s\n",__FILE__,__LINE__,s)
#else
#define Logs(s) NULL
#endif
#if HIGH
void f()
{
printf("this is the high level product\n");
}
#else
void f()
{
}
#endif
int main()
{
Log("Enter main()...");
f();
printf("1.Query Information\n");
printf("2.Record Information\n");
printf("3.Delete Information\n");
#if HIGH
printf("4.High level Query\n");
printf("5.Mannul service\n");
printf("6.Exit...\n");
#else
printf("4.Exit...\n");
#endif
Log("Exit main()...");
return 0;
}