[英]Including other header inside include guard causes error
I have few different classes. 我有几个不同的班级。 Few pairs need to know about each other. 很少有人需要彼此了解。 To prevent the headache I've created one file to keep forward declarations of all troublesome classes along with proper include order. 为了避免头痛,我创建了一个文件来保留所有麻烦类的声明以及正确的包含顺序。
#ifndef GLPROJECT_H
#define GLPROJECT_H
class MainWindow;
class Scene;
class ShaderProgram;
class Shape;
#include "ShaderProgram.h"
#include "MainWindow.h"
#include "Shape.h"
#include "Scene.h"
#endif
Every file who needs another one from the given set include this header. 每个需要给定集合中的另一个文件的文件都包含此标头。 I came up with an idea to put all includes inside include guard, so for example Shape.h
class looks like: 我想出了一个将所有include都包含在include Guard中的想法,例如Shape.h
类如下所示:
#ifndef SHAPE_H
#define SHAPE_H
#include "GLProject.h" //file above
//...class definition code
#endif
However this example produces error: field 'x' has incomplete type 'GLProject::Shape'
in file Scene.h
, which is stated after the Shape.h
in the main header (other files don't include Scene.h
explicitly). 但是,此示例产生错误: field 'x' has incomplete type 'GLProject::Shape'
文件中field 'x' has incomplete type 'GLProject::Shape'
,该Shape.h
在主头文件中Scene.h
之后声明(其他文件未明确包含Scene.h
)。
(Note that following flow is correct only for files which directly include GLProject.h
) If I'd trace the inclusion of files starting with GLProject.h
, then: 1) (请注意,以下流程仅对直接包含GLProject.h
文件是正确的。)如果我要跟踪以GLProject.h
开头的文件的包含,则:1)
Shape.h
which defines Shape.h
(after trying to include guarded GLProject.h
) Shape.h
定义Shape.h
(试图包括守卫后GLProject.h
) Scene.h
which declares viariable of type Shape
that should be already defined. Scene.h
,它声明应已定义的Shape
类型的viariable。 So no idea why does it complains that Shape
is incomplete type. 因此,不知道为什么会抱怨Shape
是不完整的类型。
What's more interesting moving inclusion of file
GLProject.h
in fileShape.h
above include guards fixes the problem. 更有趣的是,在包含GLProject.h
的文件GLProject.h
中将文件Shape.h
包含Shape.h
,可以解决该问题。 (the most important fact) (最重要的事实)
Ok. 好。 The actual problem was connected with not mentioned file Shape.cpp
which of course included Shape.h
and the fact that moving #include "GLProject.h"
before the guard were fixing the problem. 实际的问题与未提及的Shape.cpp
文件Shape.cpp
,该文件当然包括Shape.h
并且在警卫人员解决问题之前将#include "GLProject.h"
移动了。 The flow with the include directive inside the guard: 保护内部包含include指令的流:
Shape.h (def guard)
GProject.h (def guard)
...(MainWindow.h and ShaderProgram.h)...//not interesting
Shape.h (omit, because of guard)
Scene.h
GProject.h (omit, because of guard)
back to Scene.h (def guard) ERROR
While with the directive outside: 当使用外部指令时:
Shape.h
GProject.h (def guard)
...(MainWindow.h and ShaderProgram.h)...//not interesting
Shape.h
GProject.h (omit, cause of guard)
back to Shape.h (now def guard and class)
Scene.h
GProject.h (omit, because of guard)
back to Scene.h (def guard) No error - Shape defined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.