Advertisement

why isn't this working?

Started by January 13, 2001 06:51 PM
11 comments, last by Moe 24 years ago
I think you're a little confused about some of these keywords. Let me explain, and if I come across a little patronising, hopefully you'll forgive me when the program starts working

Firstly, you can't just use 'extern' to allow you to put a variable in a header file. The way you need to do it, is to put some normal variable definitions in a CPP file. Doesn't matter which, but it makes sense to put them in something like globals.cpp. Then, you put references to those global variables in the header file globals.h. This is what makes them global. The globals themselves are not in the header file: only the extern references.

Example:
      // globals.hextern LPDIRECT3D8 g_pD3D; // note: NO '=NULL' or anything!// globals.cpp, or anywhere else reallyLPDIRECT3D8 g_pD3D = NULL; // this is where you initialise it.  


That should fix any such problems you have regarding duplicated variables when it comes to link-time.

Secondly, the #pragma once directive can't stop a header being used more than once in a program. It just prevents it being used more than once for each compilation unit... ie. once for each .C or .CPP file you compile. Remember that each CPP file compiles independently to begin with, using whichever header files they need. It is only at the linker stage that they are combined into one... and therefore, any variables that are declared in header files may end up in more than one compiled CPP file, and therefore when the linker comes to put it all together, it finds duplicates. That is why you only put the actual variable definitions in one CPP file, and just put the extern declarations in the headers, which is enough to keep the compiler happy.

The #pragma once directive is roughly equivalent to using the standard inclusion guards on a header file, but is less portable. Therefore I recommend you get into the habit of putting your own inclusion guards in your own headers, like so:

#ifndef GLOBALS_H#define GLOBALS_H// ... the content of your header file here...#endif // GLOBALS_H 




Edited by - Kylotan on January 19, 2001 7:50:09 PM
When you said portability, you mean between compilers (say Borland and Microsoft), right?

I will give it a try.

Never cross the thin line between bravery and stupidity.
Advertisement
Oops! I didn''t mean to put the = NULL in the header file. my bad

quote:

Would you mind if I e-mailed you about this one Quantum?


It should probably work now, but if it still doesn''t, feel free

This topic is closed to new replies.

Advertisement