c++lnk2005

C++ LNK 2005 Error "already defined in .obj


Im getting this LNK 2005 error even though I have crated the game class using the proper header file and cpp file format as far as im aware.

Which after googling the problem for a while seems to be the main reason for this error, can anyone see what is is I messed up?

my game.h file is as follows:

#pragma once

class Game
{
public:


//Variables
char grid[9][8] = { { '#','#','#','#','#','#','#','#' },
                    { '#','G',' ','D','#',' ',' ','#' } ,
                    { '#',' ',' ',' ','#',' ',' ','#' } ,
                    { '#','#','#',' ','#',' ','D','#' } ,
                    { '#',' ',' ',' ','#',' ',' ','#' } ,
                    { '#',' ','#','#','#','#',' ','#' } ,
                    { '#',' ',' ',' ',' ',' ',' ','#' } ,
                    { '#','#','P','#','#','#','#','#' } ,
                    { '#','#','#','#','#','#','#','#' } };
int width, height;
int pX;
int pY;


char direction;
bool west;
bool north;
bool south;
bool east;
int quit;

Game();
};

My game.cpp file is:

#include "stdafx.h"
#include <String> 
#include <iostream>
#include "Game.h"

using namespace std;

//constructoer
Game::Game()
{
    width = 8, height = 8;
pX = 2;
pY = 7;


west = false;
north = true;
south = false;
east = false;
quit = 0;
}

My main is literally just creating an instance of the object at the moment

main:

 #include "stdafx.h"
 #include <String> 
 #include <iostream>
 #include "Game.cpp"
 #include "Game.h"


using namespace std;


int main()
{
    Game g;

    return 0;
}

Solution

  • When including game.cpp, you actually implement the contructor Game::Game() twice, i.e. one time in game.cpp (which is a separate translation unit) and one time in main.cpp (where you include the constructor implementation code). Hence, you get a linker error, not a compiler error.

    To solve the problem, remove the #include "game.cpp".