在 Linux 系统中,.h 文件是 头文件(Header File),主要用于 C/C++ 语言编程。以下是关于头文件的详细说明:
c
// example.h
int add(int a, int b); // 函数声明
#define PI 3.14 // 宏定义.c文件)分离,方便代码复用。#include <stdio.h> 提供标准输入输出函数的声明。/usr/include/ 等系统目录,如 stdlib.h、string.h。
c
#include <sys/socket.h> // 系统头文件用尖括号 <>.c 文件同目录,用双引号包含:
c
#include "myheader.h" // 自定义头文件用双引号 ""#ifndef 宏保护:
c
// myheader.h
#ifndef MYHEADER_H
#define MYHEADER_H
// 声明内容...
#endifvoid func();)#define MAX 100)typedef struct {...} MyStruct;)extern int global_var;).c 文件的关系.c 文件:实现具体功能(定义“怎么做”)。
// math.h (声明)
int add(int a, int b);
// math.c (实现)
int add(int a, int b) { return a + b; }
#include 会将头文件内容插入到源代码中。
bash
gcc -E main.c -o main.i # 查看预处理后的代码.c 文件和头文件结合生成可执行文件。#ifndef 保护可能导致重复声明。bash
gcc -I/path/to/headers main.c # 添加头文件搜索路径.h 文件是 C/C++ 开发中的核心组成部分,用于声明接口、促进代码复用。合理使用头文件能显著提升代码的可维护性和模块化程度。