Sign in to follow this  
Mantrid

global variable linker error?

Recommended Posts

Mantrid    188
i have a single header file that i want to declare globals in as they'll be used in multiple files (using extern seemed to cause linker errors in the first place) here's how the header is set up:
#ifndef GLOBALS_H
#define GLOBALS_H

typedef struct Entity {
	vector <Route> route;
	int nPos[2];
	int nTarget[2];
	bool bDead;
	bool bAtTarget;
} Entity;

Entity Prey;


#endif

and i've included this library in 2 cpp files. but no, once again i'm getting linker errors saying it's already been defined in another file surely the ifdefs are meant to stop stuff like that happening? or are they not too reliable? i must be missing something, im tired and probably not thinking too straight, anyone know what's going on and how i can allow other files to use this library without getting unresolved externals?
Quote:
GAI fatal error LNK1169: one or more multiply defined symbols found GAI error LNK2005: "struct Entity Prey" (?Prey@@3UEntity@@A) already defined in AStar.obj
many thanks for any help or suggestions people can give

Share this post


Link to post
Share on other sites
jflanglois    1020
You need to use the extern keyword:

Globals.h:
#ifndef GLOBALS_H
#define GLOBALS_H

struct Entity { // typedef struct is not necessary in C++
vector <Route> route;
int nPos[2];
int nTarget[2];
bool bDead;
bool bAtTarget;
};

extern Entity Prey;


#endif




Globals.cpp:
#include "Globals.h"

Entity Prey;




[edit] OK, let me explain why this is. It has to do with the C++ compilation model. When you have a instance definition in a header, and it is included in multiple cpp files, the result is that you have the same named object in two different compilation units. When the linker tries to link together these two resulting object files, it does not know what to do with the two identical objects.

Thusly, you use the extern keyword, which says: "I have an object of type Entity that is called Prey, but I will instanciate it somewhere else". This is why you then have Globals.cpp that instanciates Prey.

I hope that clarifies it a bit.


jfl.

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