mercredi 23 décembre 2020

"/usr/bin/ld : file.o : multiple definitions" but I only defined once

Because of an incoming internship, I started to re-train c++ because I am not familiar enough with it. So I am making simple games in one programm.

However whenever I try to compile my files, for each variables and functions declared in snake.h that I use in snake.cpp I have this error after compilation:

/usr/bin/ld : snake.o: (...) : multiple definitions of "snake::functionOrVariable; main.o:(...) : defined for the first time here

At first I checked if something was off in my makefile and I found nothing. Then I made sure that I never re-declared these in my snake.cpp and main.cpp files, turns out I didn't. Finally whatever I would do with the includes nothing changed.

Could you guys please help me ?

I am currently on ubuntu 19.10 with g++ 9.2.1

here are the files :

main.cpp

#include <iostream>

#include "games.h"

using namespace std;


int main (int argc, char * argv []){

    cout << "hello World !" << endl;

    snake::init();

    return 0;
}

snake.h

#ifndef __SNAKE_H__
#define __SNAKE_H__


#include <vector>
#include <utility>


namespace snake{

    //values

    bool gameOver = false;

    typedef std::pair<unsigned /*y*/, unsigned /*x*/> coord;

    std::vector<coord> theSnake (4);
    
    const unsigned ArenaY = 20;
    const unsigned ArenaX = 20;

    enum class Direction {UP, DOWN, LEFT, RIGHT};
    Direction currentDirection;

    //classes 
    class Fruit; // abstract class 
    class Apple; // standart apple -> increments score by 100 and player's size by 1
    class Banana; // increments score by 300 and player's size by 3 (grows progressively, 1 per turn and nothing else spawns during this time)
    class Durian; // decrements score by 300, almost has the same color as Banana's
    class Orange; // increments the score by 50 and decrements player's size by 1


    //functions 
    void init();

    void update();

    void spawnApple(unsigned x, unsigned y);



    void spawnApple(unsigned x, unsigned y, Fruit fruitToSpawn);

}

#endif // __SNAKE_H__

snake.cpp

#include <iostream>


#include "games.h"


using namespace std;


void init (){

    unsigned i = 0;

    // we use the reverse iterator because snake[0] will be the head, we dont want it in a corner
    for (vector<snake::coord>::reverse_iterator iter = snake::theSnake.rbegin(); iter < snake::theSnake.rend(); ++iter){
        *iter = snake::coord(0,i);
        ++i;
        cout << "[ y : " << iter->first << ", x : " << iter->second << " ], " ;
    }

}

games.h

#ifndef __GAMES_H__
#define __GAMES_H__

//this file groups all games' headers
#include "snake.h"


#endif // __GAMES_H__

(sorry if I did something wrong I'm new here and sorry for my bad english)

Aucun commentaire:

Enregistrer un commentaire