条件编译基本概念
- 条件编译的行为类似于C语言中的if…else
- 条件编译是预编译指示命令,用于控制是否编译某段代码
栗子:
#include <stdio.h>
#define c 1
int main()
{
#if (c == 1)
printf("有效哦");
#else
printf("可恶");
#endif
return 0;
}
经过预编译后 (省去<stdio.h>头文件)
int main()
{
printf("有效哦");
return 0;
}
这就是#if与if的不同之处。
可以在命令行定义 判断要用的参数
//text.c文件
#include <stdio.h>
//这里不预先宏定义c的值
int main()
{
#if (c == 1)
printf("有效哦");
#else
printf("可恶");
#endif
return 0;
}
在cmd命令行中 gcc -Dc=1 text.c -o text.i
经过预编译后 (省去<stdio.h>头文件)
int main()
{
printf("有效哦");
return 0;
}
#include的困惑
- #include的本质是将已经存在的文件内容嵌入到当前文件中
- #include的间接包含同样会产生嵌入文件内容的动作

疑问?
text.c和text.h都包含global.h那么编译时,会不会重复,导致出错
(根据经验,不会)事实证明,直觉错了
global.h
int global = 10;
text.h
#include "global.h"
void f()
{
printf("%d\n",global);
}
text.c
#include "text.h"
#include "global.h"
int main()
{
f();
return 0;
}
经过预编译后 (省去<stdio.h>头文件)
# 1 "text.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "text.c"
# 1 "text.h" 1 //预编译text.h
# 1 "global.h" 1
int global = 10; //"global.h" 出现1次
# 2 "text.h" 2
void f()
{
printf("%d\n",global);
}
# 2 "text.c" 2
# 1 "global.h" 1
int global = 10; //"global.h" 出现第2次
# 3 "text.c" 2
int main()
{
f();
return 0;
}
编译出错,global定义了两次
处理方法
- 删掉,不让头文件重复
- #ifndef…#endif
修改global.h
#ifndef _GLOBAL_H_
#define _GLOBAL_H_
int global = 10;
#endif
条件编译的意义
- 条件编译使得我们可以按不同的条件编译不同的代码段,因而可以产生不同的目标代码
- `#if…#else…#endif被预编译器处理;而if…else语句被编译器处理,必然被编译进目标代码
- 实际工程中条件编译主要用于一下两种情况:
- 不同的产品线共用一份代码
- 区分编译产品的调试版和发布版
第三条 ”产品线区分及调试代码应用 “ 的举例:
#include <stdio.h>
#ifdef DEBUG
#define LOG(s) printf("[%s:%d] %s\n", __FILE__, __LINE__, s)
#else
#define LOG(s) NULL
#endif
#ifdef 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");
#ifdef 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;
}
在cmd命令行里编译 gcc -DDEBUG text.c 产生的.exe文件输出为
[text.c:22] Enter main() ...
1. Query Information.
2. Record Information.
3. Delete Information.
4. Exit.
[text.c:38] Exit main() ...
在cmd命令行里编译 gcc -DHIGH text.c 产生的.exe文件输出为
This is the high level product!
1. Query Information.
2. Record Information.
3. Delete Information.
4. High Level Query.
5. Mannul Service.
6. Exit.
小结
- 通过编译器命令行能够定义预处理器使用的宏
- 条件编译可以避免重复包含头同一个头文件
- 条件编译是在工程开发中可以区别不同产品线的代码
- 条件编译可以定义产品的发布版和调试版
2万+

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



