Skip to content

C 头文件(Header Files)

头文件用于声明接口、类型与宏,供多源文件共享,避免重复定义。

1. 作用与内容

  • 函数原型、类型定义、宏、常量
  • 尽量只放声明,不放定义(除非 static inline 等)

2. 头文件保护

c
#ifndef MYLIB_H
#define MYLIB_H
// 声明
#endif

或使用 #pragma once(非标准但被广泛支持)。

3. 最小依赖原则

  • 尽可能前置声明,减少包含链
  • 在 .c 中包含实现所需的具体头

4. 接口与实现

c
// mylib.h
int add(int,int);

// mylib.c
#include "mylib.h"
int add(int a,int b){ return a+b; }

5. 标准库头文件

  • <stdio.h>, <stdlib.h>, <string.h>, <stdint.h>, <stdbool.h>

6. 小结

头文件是模块化与可重用的基础,重视保护宏、最小依赖与清晰的接口边界。

本站内容仅供学习和研究使用。