Jump to content
  • Advertisement
Sign in to follow this  
Mantrid

global variable linker error?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!