Archived

This topic is now archived and is closed to further replies.

C++ Include problem

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

Hi there, I have the following C++ source files: main.cpp, game.cpp and globals.h. globals.h contains golbal variables and objects. My problem is that when I include globals.h in main.cpp and in game.cpp (I need them in both places) linker says that "HWND MainWindowHandle alredy defined in xxx.obj ...". Even if I've made multiple including check with
#ifndef GLOBALS_H
#define GLOBALS_H
// Code ...
#endif
     
How can I pass that error? I'll be waiting for your advices. Thanks. [edited by - constans on February 21, 2004 6:09:19 AM]

Share this post


Link to post
Share on other sites
You can't safely instantiate global variables in a header file. Instead, you can use the extern keyword to make other files aware of the global, and then instantiate it in one (and only one) cpp file.

To make the above a bit clearer, here's an example:


//globals.h


#ifndef _GLOBAL_H_
#define _GLOBAL_H_

extern int gMyGlobalInt;

#endif


Note that all this does is tells the compiler that there's a global variable somewhere called gMyGlobalInt. It does not actually create the global variable, so if you try and use it with just the code above, it will compile, but you'll get 'unresolved external' errors.

To avoid this, you need to actually instantiate it in a cpp file.


// globals.cpp


int gMyGlobalInt = 0;


Hope this makes sense.

[edited by - Sandman on February 21, 2004 6:14:09 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Maybe you are actually declaring and defining an object in your header file instead of just declaring it?

I''m not sure of your knowledge, but you might want to read up on the One Definition Rules and the ''extern'' keyword.

Hope it helps.

Share this post


Link to post
Share on other sites
The reason #ifndef doesn''t help is all those preprocessor commands are forgotten before compilation of each .cpp file. So if main.cpp includes globals.h and game.h, and game.h also includes globals.h, globals.h will only be included once for main.cpp because of that preprocessor command. However, when compiling game.cpp, it''ll be included again since game.obj doesn''t have it yet. I hope I''m explaining this.

Basically, those preprocessor commands are for the compiler, but your problem is with the linker -- the same symbol is defined in both game.obj and main.obj.

~CGameProgrammer( );

Screenshots of your games or desktop captures -- Post screenshots of your projects. There''s already 134 screenshot posts.

Share this post


Link to post
Share on other sites