其他分享
首页 > 其他分享> > Include Guards:为什么C编译器不会自动包含每个头文件一次?

Include Guards:为什么C编译器不会自动包含每个头文件一次?

作者:互联网

参见英文答案 > Including header files in C/C++ more than once                                     6个
使用头文件时,每个头文件只应包含一次.
例如,假设我有三个班级. A级,B级和C级

类A在文件A.h中声明,类B在文件B.h中声明,类C在文件C.h中声明,它们在各自的.cpp文件中定义.
  A.cpp

#include "A.h"
class A  
{  
}  

在B.cpp文件中,以下是该类的定义.

#include "A.h"
#include "B.h"
class B  
{  
   A a;
}

同样适用于C.cpp文件.

#include "A.h"
#include "B.h"
#include "C.h"
class C  
{  
  A a;  
  B b;  
}  

现在,如果未在头文件中写入包含保护,那么g编译器将抛出错误.
我的问题是,为什么我们需要指定包含警卫?每个头文件只应包含一次并不常见吗?为什么编译器本身不处理多个包含?

解决方法:

My question is, why should we need to specify the include guards? Is it not common sense that each header file should be included only once? Why doesn’t the compiler take care of multiple includes by itself?

因为并非所有标题都是如此.可以多次包含并且能够这样做的标题的一个示例实际上是重要的是< assert>头.

尝试修复复制和粘贴文件内容的标题系统并没有任何意义.真的,我们只需要移动到better build model.

标签:c,header-files
来源: https://codeday.me/bug/20190824/1713112.html