【问题标题】:C++ Header File redefinition ErrorC++头文件重定义错误
【发布时间】:2014-04-04 19:12:35
【问题描述】:

我在 openGl 中创建一个游戏,我遇到了一个困扰我近 2 小时的问题。 主要功能在包含 World.h 的 readobj.cpp 中,我有一个使用 Ball.h 和 Stick.h 的 World.h 文件。另一方面,Ball.h 和 Stick.h 都在使用 Game.h 文件。

世界.h

#include "Ball.h"
#include "Camera.h"
#include "Stick.h"
class World
{
Ball ball[15];
Ball qBall;
Camera camera;
public:
World();
void update();
void render();
};

Stick.h

#include "Game.h"
class Stick
{
point power;
public:
void setPosition(point);
void setPower(point);
void render();
void update();
};

球.h

#include "Game.h"
class Camera
{
public:
Camera();
void update();
void render();
};

游戏.h

class point {
public:
double x,y,z;
};

我得到的错误是

g++ -Wall -c readobj.cpp -L. -lBall -lWorld -lCamera -lStick
In file included from Camera.h:1:0, from World.h:2,         from readobj.cpp:12:
Game.h:1:7: error: redefinition of ‘class point’
Game.h:1:7: error: previous definition of ‘class point’
In file included from Stick.h:1:0,
                 from World.h:3,
                 from readobj.cpp:12:
Game.h:1:7: error: redefinition of ‘class point’
Game.h:1:7: error: previous definition of ‘class point’

【问题讨论】:

标签: c++ opengl header-files


【解决方案1】:

使用包含守卫!

示例:

World.h:

#ifndef WORLD_H     // <<<<<<<<< Note these preprocessor conditions
#define  WORLD_H
#include "Ball.h"
#include "Camera.h"
#include "Stick.h"
class World
{
    Ball ball[15];
    Ball qBall;
    Camera camera;
public:
    World();
    void update();
    void render();
};
#endif // WORLD_H

说明:
如果头文件包含在其他头文件中,并且这些头文件在编译单元中冗余出现,您将收到这些 'redefinition' / 'redeclaration' 错误。
如上所示的所谓include guard条件,防止预处理器多次渲染包含的代码,从而导致此类错误。

【讨论】:

    【解决方案2】:

    您似乎没有保护您的标头不被多次包含。

    对于您的每个标题,请执行以下操作: 例如游戏.h

    #ifndef GAME_H
    #define GAME_H
    /*put your code here*/
    #endif
    

    或者另一种方式可能是每个头文件的开头,这不在标准中,但大多数编译器都支持它。

    #pragma once
    

    with 告诉编译器只包含一次标头。

    基本上,当您包含标头时,预处理器会将标头中的代码放入 .cpp 文件中。因此,如果这种情况不止一次发生,您最终会得到相同类的多个声明等。

    【讨论】:

    • @Deduplicator 这就是为什么我从正确的例子开始,但还是编辑了答案。
    • 恕我直言,pragma 是非标准的。
    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 2018-12-10
    • 2021-04-28
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多