#ifndef not working

Started by
23 comments, last by Hawkblood 10 years ago
@Buckeye

I need to have ceratin variables that can be accessed by most of the other .cpp files at some point. Please show me EXACTLY how you would accomplish this. Please give a simplified, yet complete example because I am not understanding what you mean.

@rip-off
That is essentially what I am doing and it works. When I first tried it I didn't read your code properly-- that's how I failed.
Advertisement

If you need the object GRAPHICS *GE in a lot of files:


// main.h
// declaration of GRAPHICS. Some compilers will tell:
// "warning C4091: 'typedef ' : ignored on left of 'GRAPHICS' when no variable is declared"
// you can delete the 'typedef' in that case.
typedef struct GRAPHICS
{
  // ... whatever your GRAPHICS variables/functions are - goes here, as you know
};
// if you delete "typedef" then do NOT define a variable between the immediately preceding "}" and ";"

extern GRAPHICS *GE; // forward declaration for anyone needing to access GE

// main.cpp
#include "main.h"
GRAPHICS *GE = NULL; // definition

// don't where you create GE. But..
GE = new GRAPHICS; // instantiation

// any other header or cpp file that needs access to GE
#include "main.h"

// somewhere in the code in this cpp. Don't know how you use it, but..
int number = GE->GiveMeANumber(); // some use of GE

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

That's essentially what I'm doing (now). I'm not putting the declaration of "extern GRAPHICS *GE;" in main.h, but I think I get what you mean.

There's no rule that says you have to do it any particular way. It's just a good rule of thumb. You can put "extern GRAPHICS *GE;" in any header. Provided the definition "GRAPHICS *GE;" appears in only one place in all the compiled code, the linker will find it.

As rip-off mentioned, each #include header is "pasted" into a cpp file before it's compiled, and each cpp is compiled separately into a separate obj file. Then the linker combines all the obj files into a single executable. If "GRAPHICS *GE;" appears in a header file that's included in (say) 2 cpp files, the linker ends up with something that looks like:


GRAPHICS *GE; // from one obj file
GRAPHICS *GE; // from another obj file

And, as you know, you can't have 2 variables named the same in the same space. That's where your original errors were coming from.

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

I thank you both for your help.

This topic is closed to new replies.

Advertisement