一、头文件
-
在 C++ 中,头文件(
.h
)用于函数声明、类定义、宏定义等等 -
在 Visual Studio 中,头文件通常放在头文件目录中,头文件实现通常放在源文件目录中
二、常用标准库头文件
1、输入输出
<iostream>
标准输入输出流
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl;
return 0;
}
2、容器
<string>
字符串处理
cpp
#include <string>
using namespace std;
int main() {
string s = "Hello World";
return 0;
}
<vector>
动态数组
cpp
#include <vector>
using namespace std;
int main() {
vector<int> nums = { 1, 2, 3 };
return 0;
}
3、多线程
<thread>
线程支持
cpp
#include <iostream>
#include <thread>
using namespace std;
void threadFunction() {
std::cout << "Hello Thread" << endl;
}
int main() {
thread t(threadFunction);
t.join();
return 0;
}
三、自定义头文件
- 头文件
math_utils.h
cpp
#pragma once
#include <iostream>
namespace math {
int square(int x);
void printSquare(int x);
}
- 头文件实现
math_utils.cpp
cpp
#include "math_utils.h"
namespace math {
int square(int x) {
return x * x;
}
void printSquare(int x) {
std::cout << "Square of " << x << " is " << square(x) << std::endl;
}
}
- 测试代码
math_utils_test.cpp
cpp
#include "math_utils.h"
#include <iostream>
int main() {
std::cout << math::square(5) << std::endl;
math::printSquare(4);
return 0;
}
四、头文件引入方式
1、使用双引号
cpp
#include "math_utils.h"
-
首先,编译器在当前源文件所在目录搜索
-
然后,编译器在指定的包含路径中搜索(例如,
-I
选项指定的路径) -
最后,编译器在标准系统包含路径中搜索
-
这种方式通常用于包含用户自定义的头文件
2、使用尖括号
cpp
#include <iostream>
-
编译器不会在当前目录搜索
-
编译器直接在标准系统包含路径中搜索
-
这种方式通常用于包含标准库头文件
五、防止头文件重复包含机制
1、基本介绍
-
#pragma once
是 C++ 中用于防止头文件重复包含的编译器指令 -
拿
#include "math_utils.h"
这行代码来举例,重复包含就是写了多次这行代码 -
头文件使用
#pragma once
后,当编译器首次包含头文件时,会记录该头文件的唯一标识(完整路径) -
后续再遇到相同的包含头文件时,编译器会直接跳过其内容
-
#pragma once
是传统头文件保护宏(#ifndef
/#define
/#endif
)的现代替代方案
2、演示
(1)未防止重复包含
- 头文件
math_utils.h
,未添加#pragma once
cpp
int globalVar = 10;
- 测试代码
my_header_test.cpp
,重复包含了头文件
cpp
#include "my_header.h"
#include "my_header.h"
#include <iostream>
using namespace std;
int main() {
cout << globalVar << endl;
return 0;
}
# 输出结果
C2374 "globalVar": 重定义;多次初始化
(2)防止重复包含
- 头文件
math_utils.h
,添加了#pragma once
cpp
int globalVar = 10;
- 测试代码
my_header_test.cpp
,重复包含了头文件
cpp
#include "my_header.h"
#include "my_header.h"
#include <iostream>
using namespace std;
int main() {
cout << globalVar << endl;
return 0;
}
# 输出结果
10