第八章 编译预处理(二)
第二节 文件包含和条件编译
1. 文件包含
属于编译中预处理部分,将另外一个文件的内容包含到本文件中,通过include命令来实现
一般格式: #include “文件名”,#include其他.h文件(即头文件)
我们常常把宏定义和函数说明,一些其他的include的命令,以及其他一些全局变量的外部声明等放在头文件中
说明
很多公共修改都可以放在.h文件中进行,一但修改了.h文件,也就相当于对应的.cpp文件,那么系统会重新编译对应的.cpp文件
include只能包含一个文件,如果要包含多个头文件,写多个include
文件包含是可以嵌套的,一个头文件中可以嵌套其他头文件,本质上就是把另外一个文件中的内容搬到本文件中来
include可以使用<>和" “的区别,<>是从系统目录中找对应的文件,” "是首先从当前目录去查找,找不到再到系统目录中去找
2. 条件编译
- 形式1:当标识符被定义过(#define),则对程序段1进行编译,否则对程序段2进行编译,#else部分可以没有
# ifdef 标识符 程序段1(一堆程序) #else 程序段2(一堆程序) #endif#include <iostream> #define DEBUG 1 int main() { #ifdef DEBUG printf("Now in the mode debug!\n"); #endif return 0; }- 形式2:当标识符没有被定义过(#define),则对程序段1进行编译,否则对程序段2进行编译,#else部分可以没有
# ifndef 标识符 程序段1(一堆程序) #else 程序段2(一堆程序) #endif#include <iostream> int main() { #ifndef RELEASE printf("Now in the mode debug!\n"); #endif return 0; }- 形式3:指定表达式为真,编译程序段1,若表达式2的值为真,编译程序段2,否则,编译程序段3,事先给定一定的条件下,使程序程序实现一定的功能
#if 表达式 程序段1(一堆程序) #elif 程度段2(一堆代码) #else 程序段3(一堆程序) #endif#include <iostream> //#define AGE 26 int main() { #if AGE printf("AGE is defined!\n"); #else printf("AGE is not defined!\n"); #endif return 0; }- 优点
条件编译可以减少生成的目标文件的长度
面临跨平台的问题:为了增加程序的可移植性,增加程序的灵活性
#include <iostream> int main() { #if _WIN32 WaitForSingleObject() #elif __linux__ printf("now under the linux system!"); #else //some other system #endif return 0; }