C 头文件
系统讲解 C 语言头文件(.h)的接口共享机制、尖括号与双引号搜索路径差异、#include 展开过程、#ifndef 头文件保护宏、宏计算条件包含及 14 个核心标准库头文件。
学完这一章,你能够
- 系统讲解 C 语言头文件(.h)的接口共享机制、尖括号与双引号搜索路径差异、#include 展开过程、#ifndef 头文件保护宏、宏计算条件包含及 14 个核心标准库头文件。
头文件的作用与两种 #include 引用语法
头文件是以 `.h` 为扩展名的接口声明文件,用于集中存放函数原型、宏定义、类型别名、结构体声明与 `extern` 变量声明,供多个 `.c` 源文件共享。头文件分为编译器自带的标准库头文件与开发者编写的自定义头文件两类;通过 `#include` 引用头文件比在各源文件中手工复制声明更可靠,能避免接口修改时出现多处不同步。
`#include` 支持两种搜索语法:`#include <file>` 用于系统头文件,预处理器按标准系统包含目录列表查找;`#include "file"` 用于用户自定义头文件,预处理器优先在当前源文件所在目录查找,未命中时再回退到系统目录。编译时可通过 GCC 的 `-I<dir>` 参数将自定义目录前置到搜索路径中。
包含展开、防重复包含与条件引用
从处理机制上看,`#include` 指令会让预处理器将目标头文件的内容原样插入到指令所在行,再把合并后的翻译单元交由编译器解析。例如 `program.c` 中包含声明了 `char *test(void);` 的 `header.h` 后,编译器实际看到的就是原型声明紧接在 `main()` 之前的完整源码。
在多模块工程中,同一头文件常被间接包含多次,若不做防护会引发结构体或类型重复定义错误。标准 C 的可移植做法是使用 `#ifndef HEADER_FILE` / `#define HEADER_FILE` / `#endif` 头文件保护宏(include guard):首次包含时定义保护宏并展开正文,再次包含时条件为假而整段跳过。
需要按平台或构建配置从多个头文件中择一包含时,可使用 `#if`/`#elif` 分支;当候选头文件数量较多时,C 预处理器还允许“计算包含(computed include)”——先通过宏(或 Makefile 中的 `-DSYSTEM_H="system_1.h"`)定义头文件名,再书写 `#include SYSTEM_H` 由预处理器展开查找。本站离线实验已验证保护宏幂等性与宏计算 `#include`。
ANSI / ISO C 常用标准库头文件
ANSI C(C89/C90)与 ISO C(C99/C11)定义了一组跨平台标准库头文件,覆盖输入输出、内存管理、字符串、数学、时间、字符分类、类型极值、断言、错误码、信号与本地化等基础能力(详见下方参考表)。本站离线 C11 程序已实际包含全部 14 个标准库头文件并逐项验证其核心函数与宏行为。
C 标准库常见头文件与核心功能速查表
| 头文件 | 核心能力与代表符号 |
| `<stdio.h>` | 标准输入输出与文件流操作,如 `printf`、`scanf`、`fopen`。 |
| `<stdlib.h>` | 动态内存管理、数值转换与进程控制,如 `malloc`、`free`、`strtol`、`exit`。 |
| `<string.h>` | 字符串与内存块操作,如 `strlen`、`strcmp`、`memcpy`、`memmove`。 |
| `<math.h>` | 常用数学计算函数,如 `sin`、`cos`、`sqrt`(Linux GCC 需链接 `-lm`)。 |
| `<time.h>` | 日历时间、计时器与日期格式化,如 `time`、`strftime`。 |
| `<ctype.h>` | 单字符分类与大小写转换,如 `isalpha`、`isdigit`、`tolower`。 |
| `<limits.h>` | 整数类型取值边界常量,如 `INT_MAX`、`SCHAR_MIN`。 |
| `<float.h>` | 浮点数范围、基数与精度常量,如 `FLT_MAX`、`DBL_EPSILON`。 |
| `<assert.h>` | 运行期调试断言宏 `assert`(配合 `NDEBUG` 可关闭)。 |
| `<errno.h>` | 错误码左值 `errno` 及标准错误常量宏(如 `EDOM`、`ERANGE`)。 |
| `<stddef.h>` | 通用基础类型与宏定义,如 `size_t`、`ptrdiff_t`、`NULL`、`offsetof`。 |
| `<signal.h>` | 异步信号编号与处理器注册接口,如 `signal`、`SIGINT`。 |
| `<setjmp.h>` | 非局部跳转上下文保存与恢复机制(`setjmp`/`longjmp`)。 |
| `<locale.h>` | 区域化与字符/货币格式设置,如 `setlocale`。 |
实测 C11 头文件保护宏幂等性、宏计算条件包含及 14 个标准库头文件核心接口
展开查看收起
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <locale.h>
#include <setjmp.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* Conditional / computed header inclusion via macro */
#define SELECTED_MATH_H <math.h>
#include SELECTED_MATH_H
/* Simulate include-guard idempotency across repeated inclusion */
#ifndef DEMO_HEADER_H
#define DEMO_HEADER_H
#define GUARD_INIT_COUNT 1
typedef struct {
int code;
} HeaderSample;
static const char *header_greeting(void) { return "header-ok"; }
#endif
#ifndef DEMO_HEADER_H
#define DEMO_HEADER_H
#error "Include guard failed to skip duplicate block"
#endif
static jmp_buf jump_env;
int main(void) {
/* Case 1: include guard prevents redefinition and exposes prototype */
HeaderSample hs = {GUARD_INIT_COUNT};
const char *msg = header_greeting();
int c1_pass = (hs.code == 1 && strcmp(msg, "header-ok") == 0);
/* Case 2: macro-computed conditional #include <math.h> works */
double root = sqrt(81.0);
double c0 = cos(0.0);
int c2_pass = (root == 9.0 && c0 == 1.0);
/* Case 3: core C standard headers (<string.h>, <ctype.h>, <limits.h>, <float.h>, <stddef.h>, <time.h>) */
size_t len = strlen("C11");
int is_a = isalpha((unsigned char)'C') != 0;
int is_d = isdigit((unsigned char)'1') != 0;
int limits_ok = (INT_MAX >= 32767 && FLT_MAX > 1e30f);
size_t off = offsetof(HeaderSample, code);
time_t now = time(NULL);
int c3_pass = (len == 3 && is_a && is_d && limits_ok && off == 0 && now != (time_t)-1);
/* Case 4: diagnostic & runtime control headers (<assert.h>, <errno.h>, <signal.h>, <setjmp.h>, <locale.h>) */
assert(len == 3);
errno = 0;
const char *loc = setlocale(LC_ALL, "C");
int jumped = 0;
if (setjmp(jump_env) == 0) {
longjmp(jump_env, 7);
} else {
jumped = 1;
}
int sig_ok = (SIGINT != 0);
int c4_pass = (errno == 0 && loc != NULL && jumped == 1 && sig_ok);
printf("{\n");
printf(" \"runtime\": \"GCC C11 (mstorsjo/llvm-mingw:20260616)\",\n");
printf(" \"cases\": [\n");
printf(" {\"name\": \"include_guard_idempotency\", \"expected\": \"1|header-ok\", \"actual\": \"%d|%s\", \"passed\": %s},\n",
hs.code, msg, c1_pass ? "true" : "false");
printf(" {\"name\": \"computed_header_include\", \"expected\": [9.0, 1.0], \"actual\": [%.1f, %.1f], \"passed\": %s},\n",
root, c0, c2_pass ? "true" : "false");
printf(" {\"name\": \"core_stdlib_headers\", \"expected\": {\"len\": 3, \"alpha\": true, \"digit\": true, \"limits\": true, \"offset\": 0}, \"actual\": {\"len\": %zu, \"alpha\": %s, \"digit\": %s, \"limits\": %s, \"offset\": %zu}, \"passed\": %s},\n",
len, is_a ? "true" : "false", is_d ? "true" : "false", limits_ok ? "true" : "false", off, c3_pass ? "true" : "false");
printf(" {\"name\": \"diagnostic_runtime_headers\", \"expected\": {\"errno\": 0, \"jumped\": 1, \"sig\": true}, \"actual\": {\"errno\": %d, \"jumped\": %d, \"sig\": %s}, \"passed\": %s}\n",
errno, jumped, sig_ok ? "true" : "false", c4_pass ? "true" : "false");
printf(" ]\n");
printf("}\n");
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`#ifndef` 保护宏能防止同一翻译单元内重复包含导致的类型重定义编译错误;若在头文件中直接定义全局变量,多个 `.c` 文件包含后会在链接阶段触发重复定义(multiple definition)错误,应改为头文件 `extern` 声明、单一 `.c` 文件定义。