【问题标题】:Include file includes itself with guards包含文件将自身包含在警卫中
【发布时间】:2021-04-11 21:37:04
【问题描述】:

我有两个头文件,animation.hhero.h, 这是animation.h的代码:

#include <SFML/Graphics.hpp>
#include <iostream>
#include "hero.h"

#ifndef ANIMATION
#define ANIMATION

//Class

#endif

对于hero.h

#include <SFML/Graphics.hpp>
#include <iostream>
#include "animation.h"

#ifndef HERO
#define HERO

//Class

#endif

即使使用包含防护,我也会收到错误消息 #include file "" includes itself。 我不熟悉使用包含守卫等,所以这可能是一个非常微不足道的错误。

感谢您的帮助

【问题讨论】:

  • 为什么动画中会包含英雄?我认为英雄需要动画,但动画不知道英雄或任何其他动画实体。所以你应该在需要它的 cpp 文件中包含 hero,而不是动画(如 hero.cpp)

标签: c++ include include-guards


【解决方案1】:

你应该把标题保护放在其他任何东西之前。

gccMSC你也可以使用

#pragma once

相反。可能也在其他更现代的编译器上。只需将其放在包含的顶部,而不是 #ifdef...

animation.h

#ifndef ANIMATION
#define ANIMATION

#include <SFML/Graphics.hpp>
#include <iostream>
#include "hero.h"

//Class

#endif

hero.h

#ifndef HERO
#define HERO

#include <SFML/Graphics.hpp>
#include <iostream>
#include "animation.h"

//Class

#endif

animation.h

#pragma once

#include <SFML/Graphics.hpp>
#include <iostream>
#include "hero.h"

//Class

【讨论】:

  • 这可能会消除警告和直接问题,但不会解决真正的问题。
  • 请注意,标记#pragma once“现代”并不能使它起作用。在某些情况下(例如,源文件存储在多个网络服务器上)编译器可能无法判断两个包含文件是否是“相同”文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 2019-04-25
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多