-
Multiple definitions?
In a program I'm working on, I have a header file which defines some structs. In that same header file I have 2 pointers:
Code:
Window* gwindow; // global pointer to core Window obj
Settings* gsettings; // global pointer to core Settings obj
I want to use these pointers globally throughout the program, so that wherever I include the header file, I have access to them. However, while linking I get these errors:
multiple definition of `gwindow'
first defined here
multiple definition of `gsettings'
first defined here
It must say that about 5 times each for gwindow and gsettings. What does this mean? I'm guessing everytime I include the file, it redefines the the pointer or something? How do I get around this?
-
-
Of course, you could pass the pointers around in parameters. Maybe put the pointers in the main .cpp file, and in the other .cpp files where you need them, use the 'extern' keyword (meaning you're expecting to find that pointer from a different file). I believe its like Settings* gsettings; in main.cpp, and extern Settings* gsettings; in settings.cpp. I haven't done that in a while (and I only did it once) so I'm probably wrong somehow.
If the program design is laid out right would a global, or extern, really be necessary? I can't tell, but I don't think passing references would be able to reach everything in a program (especially main()). Any other ways?
-
Hmm.. so would I put:
Code:
extern Window* gwindow;
extern Settings* gsettings;
at the beginning of each file I include the header? It still does the same thing.
-
No the other way round.
You put
Code:
extern Window* gwindow;
extern Settings* gsettings;
In the header thet gets included in severel source-files.
and define the variables in any ( one ) of your source-files.
Kurt
-
Heres some modified code for a singleton that I got out of a book. This is sort of what I was thinking of doing, but thought it would be cheesy, but this looks good. It creates an instance of Window and returns a pointer to that instance, unless one has already been created in which case it returns that instance. Hence only one instance of the class exists in the program. Both extern and this would get the job done, just passing this by. (since I do find it more elegant).
Code:
#window.h
class Window {
public:
static Window* Instance();
protected:
Window() {}
private:
static Window* m_instance;
};
Window* Window::m_instance = 0;
Window* Window::Instance () {
if(m_instance == 0) {
m_instance = new Window;
}
return m_instance;
}
It doesn't say, but I would think calling: Window* gwindow = Window::Instance(); in the files you need gwindow would work, or call it directly and skipping the gwindow part.