avoiding multiple definitions of objects

Started by
4 comments, last by JohnBolton 18 years, 10 months ago
Yes, yet another of my famous multiple def threads... (I _am_ learning!) Say I have some class, "foo". I have to have one global foo object. I am making a win32 api app, and the winproc for the main window is in a file called "winproc.cpp", included by "winproc.h", included by "main.cpp", which holds the WinMain function. If I define the foo singleton in either winproc.h or winproc.cpp, it gives me a multiple definition error. How can I avoid this? Thanks!
my siteGenius is 1% inspiration and 99% perspiration
Advertisement
I know it is stating the obvious but you are using inclusion guards in your header files right?

ace
Do not declare objects or variables in header. Use inclusion guard and if you want global objects make it "extern" and declare it in some module.
[ILTUOMONDOFUTURO]
Don't include CPP files, add them to your probject (or makefile or whatever).

Then you have foo.h and foo.cpp, and in foo.h you declare the class and it's members, and in foo.cpp you implement the members. Also, in foo.h, at the end, you can have 'extern foo GlobalFooInstance;' and in foo.cpp you have 'foo GlobalFooInstance;'
Now you can access GlobalFooInstance from any cpp file that includes foo.h, and you'll get no errors about definining it multiple times.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
Yes - I've posted enough posts about the inclusion guard thing to last me a lifetime. I'm using them :)

The extern thing was no dice though. Could you give me a short example? I tried this:

global.h
#ifndef GLOBAL_HPP#define GLOBAL_HPPextern Foo foo_object;#endif


global.cpp
#include "global.h"Foo foo_object;


Still got the multiple def error, though...
my siteGenius is 1% inspiration and 99% perspiration
No reason why you should get an error about multiple definitions in that example. The problem must be elsewhere. How and where is Foo declared?
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!

This topic is closed to new replies.

Advertisement