一、頭文件
-
在 C++ 中,頭文件(
.h
)用于函數聲明、類定義、宏定義等等 -
在 Visual Studio 中,頭文件通常放在頭文件目錄中,頭文件實現通常放在源文件目錄中
二、常用標準庫頭文件
1、輸入輸出
<iostream>
標準輸入輸出流
#include <iostream>using namespace std;int main() {cout << "Hello World" << endl;return 0;
}
2、容器
<string>
字符串處理
#include <string>using namespace std;int main() {string s = "Hello World";return 0;
}
<vector>
動態數組
#include <vector>using namespace std;int main() {vector<int> nums = { 1, 2, 3 };return 0;
}
3、多線程
<thread>
線程支持
#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
#pragma once#include <iostream>namespace math {int square(int x);void printSquare(int x);
}
- 頭文件實現
math_utils.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
#include "math_utils.h"
#include <iostream>int main() {std::cout << math::square(5) << std::endl;math::printSquare(4);return 0;
}
四、頭文件引入方式
1、使用雙引號
#include "math_utils.h"
-
首先,編譯器在當前源文件所在目錄搜索
-
然后,編譯器在指定的包含路徑中搜索(例如,
-I
選項指定的路徑) -
最后,編譯器在標準系統包含路徑中搜索
-
這種方式通常用于包含用戶自定義的頭文件
2、使用尖括號
#include <iostream>
-
編譯器不會在當前目錄搜索
-
編譯器直接在標準系統包含路徑中搜索
-
這種方式通常用于包含標準庫頭文件
五、防止頭文件重復包含機制
1、基本介紹
-
#pragma once
是 C++ 中用于防止頭文件重復包含的編譯器指令 -
拿
#include "math_utils.h"
這行代碼來舉例,重復包含就是寫了多次這行代碼 -
頭文件使用
#pragma once
后,當編譯器首次包含頭文件時,會記錄該頭文件的唯一標識(完整路徑) -
后續再遇到相同的包含頭文件時,編譯器會直接跳過其內容
-
#pragma once
是傳統頭文件保護宏(#ifndef
/#define
/#endif
)的現代替代方案
2、演示
(1)未防止重復包含
- 頭文件
math_utils.h
,未添加#pragma once
int globalVar = 10;
- 測試代碼
my_header_test.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
int globalVar = 10;
- 測試代碼
my_header_test.cpp
,重復包含了頭文件
#include "my_header.h"
#include "my_header.h"#include <iostream>using namespace std;int main() {cout << globalVar << endl;return 0;
}
# 輸出結果10