无尽的include循环

endless include loops

本文关键字:循环 include 无尽      更新时间:2023-10-16

可能重复:
C头文件循环

原始问题:

我一直很难理解为什么下面会出现错误:

something.h

#ifndef SOMETHING_H
#define SOMETHING_H
#include "somethingelse.h"
#endif

某种东西。h

#ifndef SOMETHINGELSE_H
#define SOMETHINGELSE_H
#include "something.h"
#endif

为什么会出现错误?

1( 未定义SOMETHING_H

2( 某些东西被定义,某些东西被包含在中

3( SOMETHINGELSE_H未定义,变成已定义,并且something.H包含

4( 定义了SOMETHING_H,跳转到#endif,这应该是它的结尾吗?


编辑:

事实证明它根本没有任何错误。然而,以下情况确实存在:

something.h

#pragma once
#include "somethingelse.h"
class something {
    int y;
    somethingelse b;
};

某种东西。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",并生成类的实例。

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

正如其他海报已经指出的那样,头文件很可能包含相互需要定义的类,这就是问题的原因。这类问题通常由解决

  • 尽可能使用正向参考
  • 尽可能将#include移动到CPP文件

这正是发生的事情。

这被称为"包含保护",用于避免无限递归的包含。