• 12
• 10
• 10
• 13
• 10

# Linking errors when only including once

This topic is 3674 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 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 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.