Pergunta

I am creating a Game in openGl and I encountered a problem which is bugging me for nearly 2 hours now. Main function is in readobj.cpp which includes World.h, I have a World.h file which uses Ball.h and Stick.h. In the other hand there is a Game.h file which is being used by both Ball.h and Stick.h.

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();
};

Stick.h

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

Ball.h

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

Game.h

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

The error that i am getting is

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’
Foi útil?

Solução

Use include guards!

Exemplary:

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

Explanation:
If header files are included from other header files, and these occur redundantly within compilation units, you will get these 'redefinition' / 'redeclaration' errors.
The so called include guard conditions as shown above, prevent the preprocessor rendering the included code multiple times, and thus causing such errors.

Outras dicas

You don't seem to protect you header from being included more than once.

For each of your headers do something like: eg for game.h

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

Or another way might be start every header with, this is not in the standards but most compilers do support it.

#pragma once

with tells the compiler to include the header only once.

Basically when you include the header the preprocessor puts the code from the header in the .cpp files. thus if this happens more than once, you'll end up with multiple declarations of the same classes etc.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top