C provides certain language facilities by means of a preprocessor,which is conceptually a separate first step in compilation.
The two most frequently used features are #include, to include the contents of a file during compilation, and #define, to replace a token by an arbitrary sequence of characters.
Other features described in this section include conditional compilation and macros with arguments.
【来自:《The C Programming Language(Second Edition)》 (美) Brian W.Kernighan Dennis M.Ritchie】
【C语言】C 预处理器:
- 编译器在编译程序时,预处理器在实际编译之前进行预处理:先清理代码(删除注释、多行语句合并成一个逻辑行)、执行预处理指令。
- 预处理器不是编译器的组成部分,而是编译过程中独立的第一步,是文本替代工具。
- 预处理指令常用的有#include和#define。其它的还有条件编译、带参数的宏等。
- 预处理指令必须是#开头,一般在代码开头,不需要分号结尾。
- 预处理指令一般是一行,可在行尾用"\"折返成多行。
指令 | 描述 |
---|---|
#include | 包含一个源代码文件 |
#define | 定义宏 |
#undef | 取消已定义的宏 |
#ifdef | 如果宏已经定义,则返回真 |
#ifndef | 如果宏没有定义,则返回真 |
#if | 如果给定条件为真,则编译下面代码 |
#else | #if 的替代方案 |
#elif | 如果前面的 #if 给定条件不为真,当前条件为真,则编译下面代码 |
#endif | 结束一个 #if……#else 条件编译块 |
#error | 当遇到标准错误时,输出错误消息 |
#pragma | 使用标准化方法,向编译器发布特殊的命令到编译器中 |
1、#include 引入头文件
头文件:
① 扩展名为.h的文件。
② 包含系统全局变量、宏定义、函数声明。被多个源文件引用共享。
③ 引入的头文件中,也可能引入其它头文件。
④ 有两种类型的头文件:
- 系统头文件:编译器自带的头文件。在系统目录中。
- 用户头文件:程序员编写的头文件。在当前目录中,也可能在其它目录中。若在其它目录下,需要指定路径。
#include <stdio.h> // 引入系统头文件,在系统目录下查找
#include "example.h" // 引入用户头文件,在当前目录下查找,若没有,再在系统目录下查找
#include "D:/hello.h" // 引入用户头文件,且该文件不在当前目录,而在D盘
注意:
- 一个#include指令只能引入一个头文件。引入多个头文件,需多个#include指令。
- 引入头文件的地方将替换为该头文件的内容。类似于在引入头文件的地方将该头文件内容复制粘贴,与当前源文件连接成一个源文件。
Any source line of the form #include "filename" or #include <filename> is replaced by the contents of the file filename.
引入系统头文件 | 概述 | 说明 |
---|---|---|
#include <assert.h> | 程序诊断 | 设定插入点(assert),用于程序诊断 |
#include <ctype.h> | 字符 | 判断和映射字符 |
#include <errno.h> | 错误 | 全局整型变量errno,发生错误时记录错误码 |