Global Variable Problems

Started by
2 comments, last by Tree Penguin 19 years, 4 months ago

//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?
NARF - Pinky and the Brain
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.
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 definitionOptions * 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
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.

This topic is closed to new replies.

Advertisement