蓝色天空网mbsky.com · 知识 · 实践 · 创造C · 本地阅读预览
教程 / 编程语言 / C

C 标准库 - 参考手册

对照 ISO C11/C17 标准系统总览 C 标准库全部核心头文件分类索引,涵盖 C89/C90 基础库与 C99/C11 新增定宽整数、布尔、复数与浮点环境头文件,并配套 C-ABI 偏移与目录契约验证。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

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>C99bool / true / false标准布尔类型宏(底层映射至 _Bool)
<stdint.h>C99int8_t / uint32_t / int64_t / INT64_C / size_t 极限精确位宽整数类型,消除 int/long 跨平台长度差异
<inttypes.h>C99PRId64 / PRIu32 / SCNd64 / strtoimax与 <stdint.h> 配套的跨平台 printf/scanf 格式宏
<complex.h>C99double complex / I / cabs / creal / cimag原生复数算术与复变函数支持
<tgmath.h>C99sin / sqrt / fabs 等泛型分派宏按实参浮点或复数类型自动分派至 float/double/long double/complex 版本
<fenv.h>C99fegetround / fesetround / fetestexcept / FE_TONEAREST读取与控制 IEEE 754 浮点舍入方向与异常状态标志

说明:本总览参考手册由用户授权结合 ISO C11 标准与本课程后续 21 个标准库头文件分章独立整理;本页通过离线 C-ABI 契约验证目录与结构体布局,具体每个头文件的 GCC 13.3.0 C11 编译实测见 Ch 43–63 各专章。

可运行验证实验与边界检查

python · 阅读源码
"""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 契约,全部断言一致。

离线验证 ISO C11 21 头文件目录分类、ctypes C-ABI 布局与 IEEE 754 契约

所需环境:Windows x64、CPython 3.12.14 离线 C11 标准库 21 头文件目录与 ctypes C-ABI 对齐验证器(本总览页未启动 Docker GCC;后续 21 个分头文件专章已在离线 GCC 13.3.0 C11 下逐章编译实测)。

当前源码 SHA256:bdfff353c1d7f6f213069809e60a9af0155077331b0eacf04a036acd78612875

下载本站示例源码
C 标准库 - 参考手册 — 章节实验压缩包

所需环境:Windows x64、CPython 3.12.14 离线 C11 标准库 21 头文件目录与 ctypes C-ABI 对齐验证器(本总览页未启动 Docker GCC;后续 21 个分头文件专章已在离线 GCC 13.3.0 C11 下逐章编译实测)。

ZIP SHA256:8cca178023cb653cdb6d556eed2fc41eb8b1df2932165950b74213e8d6aba8b5

常见错误与边界

  • 向 `<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);`。

规范与官方依据