Sign in to follow this  
Funkyjive

Linking errors when only including once

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this