Linking errors when only including once

Started by
2 comments, last by Funkyjive 16 years, 1 month ago
Hello again, I seem to have a small problem with my game when it comes to including a definition more than once. I believe the best way to explain it is with the troublesome code... Game.h

#ifndef _GAME_H_
#define _GAME_H_

//Inlcudes
#include "Echelon.h"

//Game Function Declarations
void GameStart(EchelonEngine* engine);
void GameEnd(EchelonEngine* engine);
void GameStep(EchelonEngine* engine);
void GameRender(EchelonEngine* engine);

//Game objects
Camera cam;

#endif
and now the echelon engine header Echelon.h

//Echelon Game Engine
#include <windows.h>
#include <gl/gl.h>
#include "Camera.h"
#include "Game.h"

#ifndef _ECHELON_H_
#define _ECHELON_H_

//engine class definition OMITTED FOR SPACE
#endif 
The error visual studio gives me is... 1>Echelon.obj : error LNK2005: "class Camera cam" (?cam@@3VCamera@@A) already defined in Game.obj I'm guessing this is a result of Game being included more than once but I thought the #ifndef took care of that. Whats going on here? Thank you!
"I would rather be in the boat with a drink on the rocks, than in the drink with a boat on the rocks" -Unknown
Advertisement
When you write Camera cam, you do not just declare the existence of cam. You also define it. So if Game.h is included in multiple source files, each will compile with their own definition of cam. Then, when you try to link the source files, the multiple definitions collide.

What you need to do is define cam in a single source file, and then declare it by prefacing Camera cam with the keyword "extern". Unlike functions, when you want to declare a variable, you must explicitly mark it so with extern.
Your include guards only offer protections from the same header content being included multiple times within a single translation unit. The problem is you've declared the global "Camera cam" in the header. Make it "extern Camera cam" and move the actual declaration to the source file instead of the header.
Thanks for the help! In light of your responses I shifted some things around and it now works. One thing I wanted to keep was the ability to keep the game files simple Game.h and Game.cpp so I fixed the problem by moving the game function declarations to there own separate header and let the engine include that and not the new Game.h which is only the declaration of the camera and anything else I need for the game. Thanks for the help.
"I would rather be in the boat with a drink on the rocks, than in the drink with a boat on the rocks" -Unknown

This topic is closed to new replies.

Advertisement