1.基本概念
条件编译的行为类似于C语言中的if…else…;
条件编译是预编译指示命令,用于控制是否编译某段代码;
可以利用预处理器调整代码、删除代码的操作。
2.编程实验
条件编译初探
//#include<stdio.h>
#define C 1
int main()
{
const char* s;
#if(1 == C)
s = “this is first printf…\n”;
#else
s = “this is second printf…\n”;
#endif
// printf("%s:", s);
return 0;
}
编译器处理后的代码为:
1 “test1.c”
1 “”
1 “<命令行>”
1 “test1.c”
int main()
{
const char* s;
s = "this is first printf...\n";
return 0;
}
运行结果:
总结:#if…#else…:用来告诉预处理器保留哪一部分代码,删除哪一部分代码。
3.条件编译的本质
预编译器根据条件编译指令有选择的删除代码
编译器不知道代码分支的存在
if. … else … 语句在运行期进行分支判断
条件编译指令在预编译期进行分支判断
可以通过命令行定义宏 :gcc -Dmacro=value file.c 或 gcc -Dmacro file.c
4.编程实验
通过命令行定义宏
方式一
#include <stdio.h>
int main()
{
const char* s;
#if( C == 1 )
s = “this is first printf…\n”;
#else
s = “this is second printf…\n”;
#endif
printf("%s", s);
return 0;
}
单步编译:gcc -DC=1 -E test2.c -o test2.i
# 1 “test2.c”
1 “”
1 “<命令行>”
1 “test2.c”
int main()
{
const char* s;
s = "this is first printf...\n";
printf("%s", s);
return 0;
}
方式二:
#include <stdio.h>
int main()
{
const char* s;
#ifdef C
s = “this is first printf…\n”;
#else
s = “this is second printf…\n”;
#endif
printf("%s", s);
return 0;
}
单步编译:gcc -DC -E test3.c -o test3.i
1 “test3.c”
1 “”
1 “<命令行>”
1 “test3.c”
int main()
{
const char* s;
s = "this is first printf...\n";
printf("%s", s);
return 0;
}
5.#include的本质
#include的本质是将已经存在的文件内容嵌入到当前文件中
#include的间接包含同样会产生嵌入文件内容的操作
条件编译可以解决头文件重复包含的编译错误
#include HEADER_FILE_H
#define HEANDER_FILE_H
// source code
#endif
6.条件编译的意义
条件编译使得我们可以按照不同的条件编译不同的代码段,因而可以产生不同的目标代码
#if…#else…#endif被预编译器处理,if…else…语句被编译器处理,必然被编译进目标代码
实际工程中条件编译主要用于以下两种情况:
不同的产品线公用一份代码
区分编译产品的调试版和发布版
7.编程实验
产品线区分及调试代码应用
product.h
#define DEBUG 1 // 调试版
#define HIGH 1 // 高端产品
product.c
#include <stdio.h>
#include “product.h”
#if DEBUG
#define LOG(s) printf("[%s:%d] %s\n", FILE, LINE, s)
#else
#define LOG(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;
}
运行结果:
8.小结
通过编译器命令行能够定义预处理器使用的宏
条件编译可以避免重复包含同一个头文件
条件编译在工程开发中可以区别不同产品线的代码
条件编译可以定义产品的发布版和调试版
————————————————
版权声明:本文为CSDN博主「小虾米_2018」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_22847457/article/details/98890674