C Header files offer the features like library functions, data types, macros, etc by importing them into the program with the help of a preprocessor directive #include​. The .h​ is the extension of it.

C++常用头文件

C++ 标准库头文件 - C++中文 - API参考文档 (apiref.com)

  • 万能头文件:#include <bits/stdc++.h>
  • 数据流输入输出:#include <iostream>
  • 算法类函数:#include <algorithm>
  • 数学函数(max(), min(), sqrt()...​):#include <math.h>​或#include <cmath>
  • 时间函数:#include <time.h>
  • 字符串操作:#include <string>​或#include <cstring>
  • 链表:#include <list>
  • 向量:#include <vector>
  • 图:#include <map>
  • 队列:#include <queue>
  • 迭代器:#include <iterator>
  • 栈:#include <stack>

引用头文件

基本语法

可以使用预处理指令#include​可以引用用户和系统头文件。引用头文件相当于复制头文件的内容。

  1. 引用系统头文件:

    1
    #include <file>
  2. 引用用户头文件:(如果在程序目录没有找到引用的头文件则到编译器的类库路径的目录下找该头文件)

    1
    #include "file"

可以用宏来定义头文件的名称,例如:

1
2
3
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H

只引用一次头文件

如果一个头文件被引用两次,编译器处理两次头文件的内容,会产生错误。为了避免,标准做法是将整个内容放在条件编译语句中:

1
2
3
4
5
6
#ifndef HEADER_FILE
#define HEADER_FILE

the entire header file file

#endif

#ifndef​是包装器,当再次引用此头文件时,条件为假,因为HEADER_FILE​已经定义,于是预处理器跳过文件的全部内容,编译器会忽视它。

类似地,#ifdef​就表示如果已经定义,就执行下面的语句。

有条件引用

有时需要依照不同情况从多个不同的头文件中选择一个引用到程序中。例如:

1
2
3
4
5
6
7
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif

头文件过多

在有多个.h​文件和多个.c​文件的时候,可以使用global.h​包含所有的头文件,然后包含global.h​文件就可以实现所有头文件的包含。

如:

1
2
3
4
5
6
#ifndef _GLOBAL_H
#define _GLOBAL_H
#include <fstream>
#include <iostream>
#include <math.h>
#include <Config.h>