为什么编译器默认不自动添加或生成包含保护?

Why doesn#39;t the compiler automatically add or generate an include guard by default?(为什么编译器默认不自动添加或生成包含保护?)

本文介绍了为什么编译器默认不自动添加或生成包含保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 C 或 C++ 代码通常需要像这样使用包含保护:

I know C or C++ code usually needs to use include guards like this:

#ifndef __A__H__
#define __A__H__
class A{
};
#endif

为了加快编译时间,在其他cpp(例如:B.cpp)中,它可以改变

and to speed up compile time, in other cpp (e.g.:B.cpp), it can change

#include "A.h"

到:

#ifndef __A__H__
#include "A.h"
#endif

但问题是为什么编译器不自动添加或生成包含保护,因此如果通常需要包含保护,程序员为什么需要手动添加?

but the question is why doesn't the compiler automatically add or generate the include guard, and therefore why does the programmer need to add it manually if an include guard is usually required?

推荐答案

有时生成标头保护是绝对不正确的.这些标准包含一个示例:C 中的 <assert.h> 和 C++ 中的 <cassert>.

There are times when it is absolutely incorrect to generate the header guard. The standards contain an example: <assert.h> in C and <cassert> in C++.

重新包含这些标头的效果取决于(重新)包含标头时 NDEBUG 宏的状态.写是合法的:

The effect of reincluding those headers depends on the state of the NDEBUG macro when the header is (re)included. It is legitimate to write:

#undef NDEBUG
#include <assert.h>
…code using assert…
#define NDEBUG 1
#include <assert.h>
…more code using assert…

如果编译器自动生成标头保护,那将无法正常工作.因此,编译器不会自动生成标头保护.

If the compiler automatically generated a header guard, that would not work correctly. Therefore, compilers do not generate header guards automatically.

顺便说一句,用户代码不应使用以双下划线或下划线大写字母开头的标头保护宏名称.这些名称是为实现而保留的.在 C++ 中,任何用户定义的名称都不能合法地包含双下划线.使用类似的东西:

Incidentally, user code should not use header guard macro names that start with double underscore, or underscore capital letter. Such names are reserved for the implementation. In C++, no user-defined name may legitimately contain a double underscore at all. Use something more like:

#ifndef A_H_INCLUDED
#define A_H_INCLUDED
…body of header…
#endif

这篇关于为什么编译器默认不自动添加或生成包含保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么编译器默认不自动添加或生成包含保护?

基础教程推荐