- 头文件中不进行任何定义,否则在多次包含时会出现多次定义的报错!
- 头文件应全面地声明,否则在调用时会出现未定义的报错。
在main.cpp中使用A.cpp中定义的函数funA()
A.h
// A.h
#include <iostream>
using namespace std;
void funA();
A.cpp
// A.cpp
#include "A.h"
void funA() {
cout << "This is funA() in A.cpp" << endl;
}
main.cpp
// main.cpp
#include "A.h"
int main() {
funA();
return 0;
}
输出:
This is funA() in A.cpp
注意:
- A.h与A.cpp可以不同名(如A.h与fA.cpp,也可达到使用fA.cpp中函数的效果),但定义函数(funA())的源文件(A.cpp)必须包含声明该函数的头文件(A.h)才能定义该函数并实现其在其他源文件中的调用(即在A.cpp中include “A.h”)。
- 若出现B.cpp与A.cpp同时include "A.h"并同时定义函数funA(),则会报错。
- 可在多个源文件中分别定义头文件中声明的不同函数。
使用全局变量
- 数值变量(int、float、数组、…)
H.h
// H.h
#include <iostream>
using namespace std;
extern int x; // 声明变量
void funA();
void funB();
A.cpp
// A.cpp
#include "H.h"
int x; // 全局变量不能在函数内部定义
void funA() {
cout << "This is funA() in A.cpp" << endl;
x = 111;
}
B.cpp
// B.cpp
#include "H.h"
void funB() {
cout << "This is funB() in B.cpp" << endl;
cout << x << endl;
x = 222;
}
main.cpp
// main.cpp
#include "H.h"
int main() {
funA();
funB();
cout << x <<endl;
return 0;
}
输出:
This is funA() in A.cpp
This is funB() in B.cpp
111
222
- 结构体
(有待研究)