Recently I have been trying to remake the classic game Snake in C++. I came across this strange error which had no logically deductible cause (I'm probably just missing something).
The error returned the message "first defined here" and then "error: ld returned exit status". Also, more curiously the C++ standard library header for deque opened up in my IDE. I use Code::Blocks as my IDE and mingw as my compiler.
#ifndef SNAKE_H_INCLUDED
#define SNAKE_H_INCLUDED
#include <deque>
class SnakeHead {
public:
int posX, posY;
private:
// Snake head functions
void input();
void movement();
// Checks if the snake ate a fruit or hit its tail or the wall
void collision_detec(int height, int width);
};
class SnakePart {
public:
// Manages snake tail
std::deque<SnakePart> parts;
// Cycles/adds tail
void advance(int x, int y, bool loose_tail);
SnakePart() = default;
private:
int x, y;
SnakePart(int x, int y) : x(x), y(y){}
};
#endif // SNAKE_H_INCLUDED
#include <conio.h>
#include "Snake.h"
#include "Game.h"
// Direction constants
enum eDirection {UP, DOWN, LEFT, RIGHT, STOP};
eDirection dir = STOP;
// Function for turning left
void turnLeft() {
switch(dir) {
case UP :
dir = LEFT;
break;
case DOWN :
dir = RIGHT;
break;
case LEFT :
dir = DOWN;
break;
case RIGHT :
dir = UP;
break;
case STOP :
dir = LEFT;
break;
}
}
// Function for turning right
void turnRight() {
switch(dir) {
case UP :
dir = RIGHT;
break;
case DOWN :
dir = LEFT;
break;
case LEFT :
dir = UP;
break;
case RIGHT :
dir = DOWN;
break;
case STOP :
dir = RIGHT;
break;
}
}
// Controls
void SnakeHead::input() {
if (kbhit()) {
switch(getch()) {
case'w' : case'W' :
if (dir == STOP)
dir = UP;
break;
case'a' : case'A' :
turnLeft();
break;
case's' : case'S' :
if (dir == STOP)
dir = DOWN;
break;
case'd' : case'D' :
turnRight();
break;
}
}
}
// Movement
void SnakeHead::movement() {
switch (dir) {
case LEFT :
--posX;
break;
case RIGHT :
++posX;
break;
case UP :
--posY;
break;
case DOWN :
++posY;
break;
}
}
void SnakeHead::collision_detec(int height, int width) {
if (posX >= width || posX < 0)
game.setGameOver();
}
SnakePart.cpp
1 2 3 4 5 6 7 8 9 10
#include "Snake.h"
void SnakePart::advance(int x, int y, bool loose_tail = true) {
parts.emplace_front(SnakePart{x, y});
if(loose_tail)
parts.pop_back();
}