如果某些函數在其他很多 cpp 文件中被調用,那么為了避免寫大量重復的代碼以及讓代碼量更小一些,我們可以將這些函數寫頭文件中,然后其他 cpp 文件只需要引用該頭文件然后就可以使用包含在頭文件中的函數了。
具體實現方法:
可以直接將函數的定義寫入一個xxx.h文件中
然后用g++ xxx.h 命令將xxx.h編譯一遍
然后在cpp源文件中用#include"xxx.h"引用即可
然而上面的方法是存在問題的,如果直接將函數的定義寫入頭文件中,那么這個頭文件如果只同時被一個 cpp 文件引用是可行的,但如果其同時被多個 cpp 文件引用是不行的。因為引用頭文件在預編譯時直接就將頭文件中的內容插入源程序。如果直接將函數定義寫在頭文件中,然后該頭文件被多個 cpp 文件引用,則這些 cpp 文件編譯生成的 obj 文件中都含有寫在頭文件中的函數的定義,所以這些 obj 文件在鏈接的時候會由於含有重復定義而報錯(c++ 中允許變量和函數的申明出現多次,但變量和函數的定義只能出現一次)。
例如:
1 //gel.h 2 3 int max_(int a, int b){ 4 return a > b ? a : b; 5 } 6 7 //test1.cpp 8 9 #include "gel.h" 10 #include <iostream> 11 using namespace std; 12 13 int main(void){ 14 cout << max_(1, 2) << endl; 15 return 0; 16 } 17 18 //test2.cpp 19 20 #include <iostream> 21 #include "gel.h" 22 using namespace std; 23 24 int main(void){ 25 cout << max_(10, 2) << endl; 26 return 0; 27 }
解決的方法:
在頭文件中只寫聲明,把定義寫到另一個cpp文件中就好啦。。
引用另一個文件的內容除了以頭文件的形式外也可以直接將函數寫入一個cpp文件,然后在需要引用的地方加個聲明,再鏈接一下就好啦。。。
事實上只要符合語法(主要是不重復定義變量,函數等),也可以將一個 cpp 文件通過頭文件引入另一個 cpp 文件中。。。
通常是將函數的聲明寫入頭文件,然后將函數體寫到其他 cpp 文件中:
1 // max.h 2 int max_(int a, int b); 3 int max_(int a, int b, int c); 4 5 // a.cpp 6 #include "max.h" 7 8 int max_(int a, int b){ 9 return a > b ? a : b; 10 } 11 12 // b.cpp 13 #include "max.h" 14 15 int max_(int a, int b, int c){ 16 return max_(a, b) > max_(b, c) ? max_(a, b) : max_(b, c); 17 } 18 19 // c.cpp 20 #include <iostream> 21 #include "max.h" 22 using namespace std; 23 24 int main(void){ 25 int a, b, c; 26 cin >> a >> b >> c; 27 cout << max_(a, b) << endl; 28 cout << max_(a, b, c) << endl; 29 return 0; 30 }