1. 什么是 #include
预处理指令 - 编译前包含指定文件内容到当前文件中,即使用包含文件替换源 文件中的#include 指令#include 指令有两种形式:#include <stdio.h> ←文件名在尖括号中 <标准系统目录>
#include “box_man.h” ←文件名在双引号中 <当前目录>
2. 头文件的作用
代码重用封装 - 把某些具有共性的函数定义放在同一个源文件里提高代码的可维护性3. 头文件的使用
test.h
//#pragma once //第一种 文件只包含一次 #ifndef TEST_H //第二种 #ifndef 和 #endif 包围的代码只包含一次 #define TEST_H #include <stdio.h> struct _pos{int x; int y; };#endif
test_A.cpp
#include <stdio.h> #include <stdlib.h> #include "test.h"//包含 "test.h" 头文件//程序员 A 的代码 int main(void){//可以使用test.h头文件中的结构体struct _pos pos;pos.x = 10;pos.y = 20;}
test_B.cpp
#include <stdio.h> #include <stdlib.h> #include "test.h"//包含 "test.h" 头文件//程序员 B 的代码 int main(void){//可以使用test.h头文件中的结构体struct _pos pos;pos.x = 10;pos.y = 20;}
4. 头文件保护措施
#pragma once //防止整个头文件被包含多次
//防止#ifndef 和#endif 包围的代码包含多次
#ifndef
…
#define
…
#endif