Headers (usually) contain entities (such as class definitions and const and constexpr variables (§ 2.4, p. 60)) that can be defined only once in any given file.
先看个例子:
#include <stdio.h>
// int max(int a, int b);
int main(){
int a=5,b=6;
printf("%d", max(a,b));
return 0;
}
// int max(int a, int b){
// return (a>b)? a:b;
double max(double a, double b){
return (a>b)? a:b;
}
这样两个文件的项目在编译的时候, 注释部分和主题有差别 其实之前提过, 对于未提前声明或定义的函数, 编译器会猜函数类型, 所以不稳定 如何解决上面的问题呢? (不声明, 不定义的情况下)
头文件
把函数原型或全局变量的声明「declaration」放到一个头文件 (以.h结尾) 中
对外公开内容
- 函数原型写入.c
- 在需要调用和被调用的源码文件 (.c文件) 中
#include
这个头文件, - 就能让编译器在编译的时候知道函数的原型
- 在需要调用和被调用的源码文件 (.c文件) 中
- 全局变量
extern
在前面加上 声明没有初始化, 初始化时定义的时候做的
不对外公开的内容
- 在函数前面加上
static
就使得它成为只能在所在的编译单元中被使用的函数 - 在全局变量前面加上
static
就使得它成为只能在所在的编译单元中被使用的全局变量
Standard Header File Structure
- 只有声明可以被放在头文件中, 但这是规则, 不是法律. 这会造成一个项目中多个编译单元里有重名的实体
- 同一个编译单元, 同名的结构不能被重复声明, 由于很难对这头文件在一个编译单元内不被include多次, 所以需要标准头文件结构
#ifndef HEADER_FLAG_H
#define HEADER_FLAG_H
// 内容
#endif
意思是
- if 没有定义后面的宏 就干下面的事 直到endif
- else 定义了没有表达式可干
为什么头文件里要有这种东西?不要正推 通过了解现象加强理解: 试想 哪天 a.cpp 包括了一个a.h b.h 又b.h包括了a.h 这样一来 a.cpp间接或直接地包括了两次a.h 譬如a.h里面变量函数类型声明,其中
- 类型只能声明一次 其余两个可以重复
- 因此此处借助判断宏是否被定义而判断该头文件是否被多次包括
- 由于这个宏没有别的特殊意义了 因此用头文件名命名再合适不过了
那么反正有这个 header guard,为什么不能在 header 中定义实体呢?
Headers Should Not Include using
Declarations
Library Headers
the names defined in the c
name headers are defined inside the std
namespace, whereas those defined in the .h
versions are not.
Using the .h
headers puts the burden on the programmer to remember which library names are inherited from C and which are unique to C++. (C++ Primer, p91)