包括其他头部包括防护导致错误

时间:2014-07-18 21:00:02

标签: c++ include include-guards

我的课程很少。很少有人需要彼此了解。为了防止头痛我已经创建了一个文件来保持所有麻烦类的声明以及正确的包含顺序。

#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

每个需要给定集合中另一个文件的文件都包含此标题。我提出了一个想法,将所有包含在内部包括后卫,所以例如Shape.h类看起来像:

#ifndef SHAPE_H
#define SHAPE_H

#include "GLProject.h" //file above

//...class definition code

#endif

但是,此示例在文件field ‘x’ has incomplete type ‘GLProject::Shape’中产生错误:Scene.h,在主标题中Shape.h之后显示(其他文件不包含Scene.h明确)。

(请注意,以下流程仅适用于直接包含GLProject.h)的文件 如果我追踪包含以GLProject.h开头的文件,那么: 1)

  1. 它包含第一个标题,但不包含任何标题
  2. MainWindow包括GLProject.h但由于包括警卫而完全省略,
  3. Shape.h定义Shape.h(在尝试包含有保障的GLProject.h之后)
  4. Scene.h声明应该已经定义的类型Shape的变量。
  5. 所以不知道为什么它会抱怨Shape是不完整的类型。

      

    在文件中移动包含文件GLProject.h更有意义   上面的Shape.h包括警卫解决问题。   (最重要的事实)

1 个答案:

答案 0 :(得分:1)

确定。实际问题与未提及的文件Shape.cpp有关,当然包括Shape.h以及在警卫面前移动#include "GLProject.h"解决问题的事实。 在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

在指令外面:

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
相关问题