Reputation: 81
Hi I'm currently working on a program in C++ and my IDE is obviously VC++ and I came across this linker error.
error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
I looked up how to fix it but none of the links got it fixed. So I thought I ask you all myself. These are all my files
Game.h
Graphics.h
Inc.h
Main.h
Game.cpp
Graphics.cpp
Main.cpp
WndProc.cpp
and in all of the header files I have the
#ifndef ...
#define...
..
#endif
and I also have some includes in the header files.
in Inc.h I have this between the #ifndef and #define
#include <Windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include "Game.h"
#include "Graphics.h"
in Main.h I have this between the #ifndef and #define
#include "Inc.h"
and I've also created to objects Game and Graphics objects
extern Game TheGame;
extern Graphics TheGraphics
I've also declared 1 function
LRESULT CALLBACK WndProc(HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam);
That's Main.h
In Game.h and Graphics.h I have this before the #ifndef and #define
#include "Main.h"
and in Game.h I have made a class called Game and a enum called GAMESTATE. In Graphics.h I have made a class called Graphics.
All the .cpp files for the class only include their class header and WndProc includes Main.h
and after all that I get this when I compile.
1>Graphics.obj : error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
1>Graphics.obj : error LNK2005: "class Game TheGame" (?TheGame@@3VGame@@A) already defined in Game.obj
1>Main.obj : error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
1>Main.obj : error LNK2005: "class Game TheGame" (?TheGame@@3VGame@@A) already defined in Game.obj
1>WndProc.obj : error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
1>WndProc.obj : error LNK2005: "class Game TheGame" (?TheGame@@3VGame@@A) already defined in Game.obj
1>F:\Games\Zombie Lypse\Release\Zombie Lypse.exe : fatal error LNK1169: one or more multiply defined symbols found
please help I've looked everywhere and I've tried to fix it myself. Still nothing.
Upvotes: 3
Views: 8403
Reputation: 14039
You have externed the globals everywhere but not defined it anywhere.
extern
doesn't define variables. It just tells the compiler that the variable is defined elsewhere. So you have to actually define it elsewhere.
You can do this.
In the header file
/* main.h */
MYEXTERN Game TheGame;
MYEXTERN Graphics TheGraphics
In the first .c file
In main.cpp
/* MYEXTERN doesn't evaluate to anything, so var gets defined here */
#define MYEXTERN
#include "main.h"
In the other .cpp files
/* MYEXTERN evaluates to extern, so var gets externed in all other CPP files */
#define MYEXTERN extern
#include "main.h"
So it gets defined in only one .cpp file & gets externed in all the others.
Upvotes: 3