Jump to content
  • Advertisement
Sign in to follow this  
TheProx

Global Variable Problems

This topic is 4949 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

//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
Advertisement
In the header you need to declare it as extern and then define it at namespace scope in one of your source files. (Basically repeat the struct Options *GameOptions; thing.)

For more information see this article.

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

  • Advertisement
×

Important Information

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

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!