为什么在 C++ 中包含两次头文件是有效的? [英] Why it's valid to include a header file twice in c++?

查看:41
本文介绍了为什么在 C++ 中包含两次头文件是有效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "DLLDefines.h"
#include "DLLDefines.h"

上面其实编译通过了,但是为什么呢?

The above actually passed compilation, but why?

推荐答案

嗯,这是合法的,因为它必须是合法的.因为您经常在没有意识到的情况下多次包含相同的标头.

Well, it's legal because it has to be legal. Because you often include the same header multiple times without even realizing it.

您可能在一个 .cpp 文件中包含两个标头,每个标头都包含多个文件,其中一些文件可能被两者都包含.

You might include two headers in a .cpp file, each of which include a number of files, some of which might be included by both.

例如,所有标准库标头(例如,stringvector)可能都包含在您的大多数标头中.因此,您很快就会在同一个 .cpp 文件中多次间接包含相同的标头.

For example, all the standard library headers (say, string or vector for example) are probably included in most of your headers. So you quickly end up with the same header being indirectly included multiple times in the same .cpp file.

简而言之,它必须工作,否则所有 C++ 代码都会崩溃.

So in short, it has to work, or all C++ code would fall apart.

至于如何工作,通常通过包含守卫.请记住,#include 只是执行简单的复制/粘贴:它会在 #include 站点插入头文件的内容.

As for how it works, usually through include guards. Remember that #include just performs a simple copy/paste: it inserts the contents of the header file at the #include site.

假设您有一个包含以下内容的头文件 header.h:

So let's say you have a header file header.h with the following contents:

class MyClass {};

现在让我们创建一个包含它两次的 cpp 文件:

now let's create a cpp file which includes it twice:

#include "header.h"
#include "header.h"

预处理器将其扩展为:

class MyClass {};
class MyClass {};

这显然会导致错误:同一个类被定义了两次.所以这是行不通的.相反,让我们修改标题以包含包含守卫:

which obviously causes an error: the same class is defined twice. So that doesn't work. Instead, let's modify the header to contain include guards:

#ifndef HEADER_H
#define HEADER_H

class MyClass {};

#endif

现在,如果我们将它包含两次,我们会得到:

Now, if we include it twice, we get this:

#ifndef HEADER_H
#define HEADER_H

class MyClass {};

#endif

#ifndef HEADER_H
#define HEADER_H

class MyClass {};

#endif

这就是预处理器处理它时发生的情况:

And this is what happens when the preprocessor processes it:

#ifndef HEADER_H // HEADER_H is not defined, so we enter the "if" block
#define HEADER_H // HEADER_H is now defined

class MyClass {};// MyClass is now defined

#endif           // leaving the "if" block

#ifndef HEADER_H // HEADER_H *is* defined, so we do *not* enter the "if" block
//#define HEADER_H
//
//class MyClass {};
//
#endif           // end of the skipped "if" block

所以,最终结果是 MyClass 只定义了 一次,即使标题被包含了两次.所以结果代码是有效的.

So, the end result is that MyClass got defined only once, even though the header was included twice. And so the resulting code is valid.

这是头文件的一个重要属性.始终定义您的标题,以便多次包含它们是有效的.

This is an important property of header files. Always define your headers so that it is valid to include them multiple times.

这篇关于为什么在 C++ 中包含两次头文件是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆