gpt4 book ai didi

c++ - 为什么在c++中两次包含一个头文件是有效的?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:57 27 4
gpt4 key购买 nike

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

上面居然编译通过了,但是为什么呢?

最佳答案

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

您可以在一个 .cpp 文件中包含两个 header ,每个 header 包含多个文件,其中一些文件可能同时包含在两者中。

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

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

至于如何它是如何工作的,通常是通过 include guards。请记住,#include 只是执行简单的复制/粘贴:它将头文件的内容插入到 #include 站点。

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

class MyClass {};

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

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

预处理器将其扩展为:

class MyClass {};
class MyClass {};

这显然会导致错误:同一个类被定义了两次。所以那是行不通的。相反,让我们修改 header 以包含 include guards:

#ifndef HEADER_H
#define HEADER_H

class MyClass {};

#endif

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

#ifndef HEADER_H
#define HEADER_H

class MyClass {};

#endif

#ifndef HEADER_H
#define HEADER_H

class MyClass {};

#endif

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

#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 只被定义了 一次,即使 header 被包含了两次。因此生成的代码是有效的。

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

关于c++ - 为什么在c++中两次包含一个头文件是有效的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3537260/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com