【问题标题】:endless include loops [duplicate]无尽的包含循环[重复]
【发布时间】:2011-10-30 18:40:34
【问题描述】:

可能重复:
C header file loops

原问题:

我总是无法理解为什么以下会出现错误:

something.h

#ifndef SOMETHING_H
#define SOMETHING_H

#include "somethingelse.h"

#endif

somethingelse.h

#ifndef SOMETHINGELSE_H
#define SOMETHINGELSE_H

#include "something.h"

#endif

为什么会报错?

1) SOMETHING_H 未定义

2) SOMETHING_H 被定义,somethingelse.h 被包括进来

3) SOMETHINGELSE_H 未定义,已定义,并包含 something.h

4) 定义了SOMETHING_H,跳转到#endif,这应该是结束了吧?


编辑:

事实证明它根本没有给出任何错误。但是,以下是:

something.h

#pragma once

#include "somethingelse.h"

class something {
    int y;
    somethingelse b;
};

somethingelse.h

#pragma once

#include "something.h"

class somethingelse {
    something b;
    int x;
};

这是合乎逻辑的,因为当 'somethingelse' 需要该类的实例时,尚未定义类 'something'。

前向定义解决了问题:

something.h

#pragma once

class somethingelse;

class something {
    int y;
    somethingelse* pB; //note the pointer. Correct me if I'm wrong but I think it cannot be an object because the class is only declared, not defined.
};

在 .cpp 中,您可以包含“somethingelse.h”,并创建类的实例。

【问题讨论】:

  • 该代码根本不应该出错...你得到了什么?
  • 等等,什么,这不会给我错误 O.o 在学校我了解到包含守卫不能防止无休止的包含循环 O.o。仅在文件 A 包含 B 和 C,并且文件 B 包含 C 的情况下,它只会包含 C 一次。嗯
  • 他没有显示的类型不完整。

标签: c++ include-guards


【解决方案1】:

您的描述完全正确,只是没有任何错误。在各个位置添加pragma message("Some text")(假设是Visual Studio)以跟踪流程。

正如其他发帖者已经指出的那样,您的头文件很可能包含相互需要彼此定义的类,这就是问题的原因。这类问题通常可以通过

  • 尽可能使用前向引用
  • 尽可能将#includes 移至 CPP 文件

【讨论】:

  • 那么为什么?您的建议是正确的,我知道如何解决问题,但是为什么类需要彼此定义是一个问题?它们只包含一次,所以我没有发现问题?
  • 假设您编译了something.cpp,其中包括something.h。这导致您假设已看到 Something 的类定义。但它没有,因为编译器首先分支到somethingelse.h。在那里,Somethingelse 类需要 Something 的定义,尽管它是 #includes something.h,但这并没有帮助,因为 SOMETHING_H 已经定义了。
【解决方案2】:

这正是发生的事情。

这称为“包含保护”,用于避免无限递归包含。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2020-08-24
    • 2019-06-10
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多