Redefinition errors?

I have five files right now: main.cpp, food.cpp, food.h, apple.cpp and apple.h. I want to make food an abstract class and create a food array in the main.cpp. It seems also to have problems with the #include statements because they get included several times and it causes redefinition errors. The #include statements of the five files are as follow:

// main.cpp
#include "Food/Food.h"
#include "Food/Apple.h"
// Food.cpp
#include "Food.h"

void Food::draw(uint8_t positionX, uint8_t positionY, uint8_t state) { }
// Food.h
#include <stdint.h>
#include "Pokitto.h"

class Food
{
public:
    // Public member variables
    uint8_t saturationPoints;
    uint8_t weightPoints;
    uint8_t happinessPoints;

    // Public member functions
    virtual void draw(uint8_t positionX, uint8_t positionY, uint8_t state) = 0;
};
// Apple.cpp
#include "Apple.h"
#include "../Graphic.h"

extern Pokitto::Core game;

Apple::Apple()
{
    Food::saturationPoints = 5;
    Food::weightPoints = 5;
    Food::happinessPoints = 5;
}

void Apple::draw(uint8_t positionX, uint8_t positionY, uint8_t state)
{
    switch (state)
    {
    case 1:
        game.display.drawBitmap(positionY, positionY, apple_1);
        break;
    case 2:
        game.display.drawBitmap(positionY, positionY, apple_2);
        break;
    case 3:
        game.display.drawBitmap(positionY, positionY, apple_3);
        break;
    }
}
// Apple.h
#include "Food.h"

class Apple : Food
{
public:
    // Public member functions
    Apple();
    void draw(uint8_t positionX, uint8_t positionY, uint8_t state);
};

In the main class I want to make a food array as global variable and add (for example an instance of the Apple class) or modify array elements.

1 Like

The problem here is that you need either include guards or #pragma once to stop your header files being included multiple times.

The easiest option is to simply put #pragma once at the top of your header files.

Technically #pragma once is non-standard, but every good modern compiler supports it.

The alternative, include guards, is a means of using preprocessor macros to conditionally include things manually, e.g.

#ifndef APPLE_H
#define APPLE_H

// Apple.h
#include "Food.h"

class Apple : Food
{
public:
    // Public member functions
    Apple();
    void draw(uint8_t positionX, uint8_t positionY, uint8_t state);
};

#endif

Wikipedia has an article about include guards if you want to know more, though I recommend preferring #pragma once.


Regarding the decision to make Apple inherit from Food,
I’d suggest you have a read of this when you have the time.
It’s a chapter from a book by Bob “Munificent” Nystrom called Game Programming Patterns.
I think you’ll find it interesting.

1 Like

Thanks! :slight_smile:

1 Like