Sign in to follow this  
TheProx

Global Variable Problems

Recommended Posts

//In Options.h
#ifndef _OPTIONS_
#define _OPTIONS_

struct Options
{
//blah
};

struct Options *GameOptions;

#endif

//elsewhere in winmain.cpp
#include "options.h"

//...
GameOptions = new Options;
//...


//in CObject.cpp
#include "options.h"

//...


Everything should work fine, right??? Compile, yes: link, no! Nope, this error is returned.
Quote:
Object.obj : error LNK2005: "struct Options * GameOptions" (?GameOptions@@3PAUOptions@@A) already defined in winmain.obj
Has anyone had this problem before, or know how to fix it?

Share this post


Link to post
Share on other sites
I think the "struct Options *GameOptions;" definition after declaring the the struct with all its variables is wrong.
Leave out the keyword struct, as you define something like a new type with your struct definition.

Like that:

struct Options
{
//bla
//...
};


//now the definition
Options * GameOptions;




That should work.

(In fact the compiler tells you the same: you are trying to redefine the struct "Options" with your line "struct Options *GameOptions;" ;) )

Good luck,
Marco

Share this post


Link to post
Share on other sites
No, the struct before declaring that variable is wrong (not sure what it does do but it isn't neccessery for you for sure) but that doesn't cause the link error. SiCrane is right, what you do now is saying "i want to allocate memory for a pointer called GameOptions" and everytime that header is included you do the same for the exact same variable.

To allocate it only once you will have to refer to an extern variable inside the header file (extern type name;) and then declare the variable in a normal way in *one* of your source files.

Every sourcefile that includes the header can access that same variable now.

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