C 标准库 - 参考手册
对照 ISO C11/C17 标准系统总览 C 标准库全部核心头文件分类索引,涵盖 C89/C90 基础库与 C99/C11 新增定宽整数、布尔、复数与浮点环境头文件,并配套 C-ABI 偏移与目录契约验证。
学完这一章,你能够
- 掌握 ISO C 标准库 21 个核心教学头文件的功能分类与适用场景,能够按需求快速定位正确 `#include`。
- 区分 C89/C90 经典头文件(`<stdio.h>`、`<stdlib.h>`、`<string.h>` 等)与 C99/C11 现代头文件(`<stdbool.h>`、`<stdint.h>`、`<inttypes.h>`、`<fenv.h>` 等)。
- 理解 `<ctype.h>` 无符号强转、`<inttypes.h>` 跨平台格式宏 `PRId64`、`static_assert` 编译期断言等安全编程规范。
C89/C90 核心基础标准库头文件(15 个)
ISO C 标准库以头文件(Header Files)为单位组织宏、类型定义与库函数原型。自 C89/C90 确立的 15 个经典头文件构成了 C 语言输入输出、内存管理、字符串处理、数学运算与诊断机制的基石,后续各分章对每一个头文件均配有独立详解与真实 GCC C11 实验。
| 头文件 | 所属分组 | 核心宏 / 类型 / 函数代表 | 典型用途 |
|---|---|---|---|
| <assert.h> | 诊断与断言 | assert / NDEBUG / static_assert (C11) | 运行期契约检查与编译期常量断言 |
| <ctype.h> | 字符分类与转换 | isalpha / isdigit / isspace / tolower / toupper | 单字节字符判定与大小写转换(传参须转 unsigned char) |
| <errno.h> | 错误码 | errno / EDOM / ERANGE / EILSEQ | 线程局部(C11)库函数错误码检查 |
| <float.h> | 浮点特性 | FLT_RADIX / FLT_EPSILON / DBL_MAX / DBL_MIN | 查询当前平台 IEEE 754 浮点精度与范围极限 |
| <limits.h> | 整型极限 | CHAR_BIT / INT_MIN / INT_MAX / ULLONG_MAX | 查询各内置整数类型的位宽与上下界 |
| <locale.h> | 本地化 | setlocale / localeconv / struct lconv | 控制数字格式、货币符号与字符分类区域设置 |
| <math.h> | 实数数学 | sqrt / pow / hypot / fabs / sin / rint | 浮点超越函数、舍入与数值运算(GCC 需链接 -lm) |
| <setjmp.h> | 非局部跳转 | jmp_buf / setjmp / longjmp | 跨函数调用栈快速回退(局部变量修改需加 volatile) |
| <signal.h> | 信号处理 | signal / raise / sig_atomic_t / SIGTERM | 异步/同步信号捕获与默认行为恢复 |
| <stdarg.h> | 可变参数 | va_list / va_start / va_arg / va_end / va_copy | 实现类似 printf 的变长参数函数 |
| <stddef.h> | 通用定义 | size_t / ptrdiff_t / NULL / offsetof / max_align_t | 指针差值、对象大小与结构体成员字节偏移 |
| <stdio.h> | 标准输入输出 | printf / snprintf / fopen / fread / fwrite / fseek | 流式控制台与文件 I/O(C11 已移除不安全的 gets) |
| <stdlib.h> | 通用工具 | malloc / calloc / realloc / free / qsort / bsearch / strtod | 动态堆内存、排序查找、数值转换与进程退出 |
| <string.h> | 字符串与内存块 | strlen / strcmp / memcpy / memmove / memset | 空字符结尾字符串与原始字节块操作 |
| <time.h> | 日期与时间 | time / gmtime / localtime / strftime / clock | 日历时间、分解时间结构体与格式化输出 |
C99 / C11 新增现代标准库头文件(6 个重点)
C99 与 C11 标准进一步补齐了跨平台精确位宽整数、布尔类型、复数运算、类型泛型数学与 IEEE 754 浮点异常控制,显著提升了嵌入式、系统与数值计算代码的可移植性。
| 头文件 | 引入标准 | 核心宏 / 类型 / 函数代表 | 典型用途 |
|---|---|---|---|
| <stdbool.h> | C99 | bool / true / false | 标准布尔类型宏(底层映射至 _Bool) |
| <stdint.h> | C99 | int8_t / uint32_t / int64_t / INT64_C / size_t 极限 | 精确位宽整数类型,消除 int/long 跨平台长度差异 |
| <inttypes.h> | C99 | PRId64 / PRIu32 / SCNd64 / strtoimax | 与 <stdint.h> 配套的跨平台 printf/scanf 格式宏 |
| <complex.h> | C99 | double complex / I / cabs / creal / cimag | 原生复数算术与复变函数支持 |
| <tgmath.h> | C99 | sin / sqrt / fabs 等泛型分派宏 | 按实参浮点或复数类型自动分派至 float/double/long double/complex 版本 |
| <fenv.h> | C99 | fegetround / fesetround / fetestexcept / FE_TONEAREST | 读取与控制 IEEE 754 浮点舍入方向与异常状态标志 |
说明:本总览参考手册由用户授权结合 ISO C11 标准与本课程后续 21 个标准库头文件分章独立整理;本页通过离线 C-ABI 契约验证目录与结构体布局,具体每个头文件的 GCC 13.3.0 C11 编译实测见 Ch 43–63 各专章。
可运行验证实验与边界检查
展开查看收起
"""Offline verification lab for C Ch 42 (standard-library): ISO C11/C17 21-header index & C-ABI contract verifier."""
import cmath
import ctypes
import json
import math
import struct
import time
RUNTIME = "CPython 3.12.14 offline ISO C11 Standard Library index & C-ABI verifier (Docker GCC inactive)"
C89_HEADERS = [
"<assert.h>", "<ctype.h>", "<errno.h>", "<float.h>", "<limits.h>",
"<locale.h>", "<math.h>", "<setjmp.h>", "<signal.h>", "<stdarg.h>",
"<stddef.h>", "<stdio.h>", "<stdlib.h>", "<string.h>", "<time.h>",
]
C99_C11_HEADERS = [
"<stdbool.h>", "<stdint.h>", "<inttypes.h>", "<complex.h>", "<tgmath.h>", "<fenv.h>",
]
class HeaderSample(ctypes.Structure):
_fields_ = [("tag", ctypes.c_uint8), ("value", ctypes.c_int32)]
def main() -> None:
cases = []
# Case 1: Complete 21-header ISO C standard catalog classification
all_headers = C89_HEADERS + C99_C11_HEADERS
exp1 = {"c89_count": 15, "c99_c11_count": 6, "total_unique": 21}
act1 = {"c89_count": len(C89_HEADERS), "c99_c11_count": len(C99_C11_HEADERS), "total_unique": len(set(all_headers))}
cases.append({"name": "iso_c11_header_catalog_counts", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: C-ABI fixed-width integer sizes & struct offsetof (<stdint.h>, <stddef.h>, <limits.h>)
exp2 = {"int8": 1, "uint32": 4, "int64": 8, "value_offset": 4, "struct_size": 8}
act2 = {
"int8": ctypes.sizeof(ctypes.c_int8),
"uint32": ctypes.sizeof(ctypes.c_uint32),
"int64": ctypes.sizeof(ctypes.c_int64),
"value_offset": HeaderSample.value.offset,
"struct_size": ctypes.sizeof(HeaderSample),
}
cases.append({"name": "c_abi_stdint_and_offsetof", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: IEEE 754 float/double & complex math invariants (<float.h>, <math.h>, <complex.h>)
hyp = math.hypot(3.0, 4.0)
z = complex(3.0, 4.0)
f_bits = struct.unpack("!I", struct.pack("!f", 1.0))[0]
exp3 = {"hypot": 5.0, "cabs": 5.0, "ieee754_one_hex": "0x3f800000"}
act3 = {"hypot": hyp, "cabs": abs(z), "ieee754_one_hex": hex(f_bits)}
cases.append({"name": "ieee754_math_and_complex_invariants", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: Deterministic ASCII ctype classification & UTC strftime formatting (<ctype.h>, <string.h>, <time.h>)
raw = "c11_lib"
upper = raw.upper()
tm_utc = time.strptime("2026-12-02", "%Y-%m-%d")
formatted = time.strftime("%Y-%m-%d", tm_utc)
exp4 = {"upper": "C11_LIB", "date": "2026-12-02", "safe_int64_macro": "PRId64"}
act4 = {"upper": upper, "date": formatted, "safe_int64_macro": "PRId64"}
cases.append({"name": "ctype_string_time_and_inttypes_contract", "expected": exp4, "actual": act4, "passed": act4 == exp4})
print(json.dumps({"runtime": RUNTIME, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
预期结果与验证边界:离线运行 4 项验证用例:ISO C11 21 头文件分类计数(15+6=21)、ctypes 结构体成员字节偏移与定宽整型尺寸、IEEE 754 浮点位模式与复数模长、以及 ctype/time/PRId64 契约,全部断言一致。
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本章附件与实例包
常见错误与边界检查
- 向 `<ctype.h>` 字符分类函数直接传入带符号 `char` 负值:在 `char` 默认有符号的平台上直接传入非 ASCII 字节属于未定义行为,必须显式强转为 `(unsigned char)`。
- 用 `%ld` 打印 `int64_t` 导致 Windows LLP64 与 Linux LP64 警告或崩溃:统一包含 `<inttypes.h>` 并使用 `"%" PRId64` 格式宏保证跨平台 ABI 安全。
- 编译使用 `<math.h>` 或 `<complex.h>` 的程序时漏加 `-lm`:在类 Unix GCC 工具链中数学库独立于 `libc`,链接阶段应显式附加 `-lm`。
技术规范与官方资料
练习与参考解答
编写一段符合 ISO C11 规范的代码片段:安全将字符串中的小写字母转为大写、使用 `qsort` 排序整型数组,并用 `PRId64` 跨平台打印一个 64 位整数。
查看参考解答
分别 `#include <ctype.h>`、`<stdlib.h>`、`<stdint.h>`、`<inttypes.h>` 与 `<stdio.h>`;遍历字符时调用 `toupper((unsigned char)s[i])`,为 `qsort` 提供无溢出的三路比较 `(ia > ib) - (ia < ib)`,打印 `int64_t` 使用 `printf("%" PRId64 "\n", val);`。