版权声明:本文为博主原创文章,未经博主允许不得转载。

 

  关于头文件重复包含的问题,以前一直不太清楚,今天特意翻了一下参考书和网上查阅资料,有了如下的理解:

  这样说明,如果定义了头文件A.h,B.h和源文件C.cpp。如果我们在A.h中写上一个函数,在B.h中include A.h,然后再在C.cpp中include A.h和B.h,这样我们就会出现重复包含的问题,如下图:

头文件重复包含问题

下面看下问题代码:

 1 ////////////////////////////////////////////////////////////////////////////////////////////////////                   A.h  files
 2 
 3 //用于测试头文件的重复包含和重定义的问题
 4 #include <iostream>
 5 using namespace std;
 6 
 7 int sub(int a, int b)
 8 {
 9     std::cout << "sub: a-b = " << a - b << std::endl;
10     return a - b;
11 }
12 
13 int add(int a, int b)
14 {
15     std::cout << "sub: a+b = " << a + b << std::endl;
16 
17     return a + b;
18 }
19 
20 
21 ////////////////////////////////////////////////////////////////////////////////////////////////////                   B.h  files
22 
23 #include <iostream>
24 using namespace std;
25 
26 #include "A.h"
27 
28 int mul(int a, int b)
29 {
30     std::cout << "sub: a*b = " << a * b << std::endl;
31 
32     return a * b;
33 }
34 
35 
36 
37 ////////////////////////////////////////////////////////////////////////////////////////////////                C.cpp files
38 
39 #include <iostream>
40 using namespace std;
41 
42 #include "A.h"
43 #include "B.h"
44 
45 int main(void)
46 {
47 
48     //add(1, 2);
49     //sub(45, 45);
50 
51     return 0;
52 }
Multiple define error: 1

相关文章: