macros declaration in headers

hi,

I have doubt about macros declaration in header files..

I saw one example in that header files are declared like this..

if temp.h is a header file
inside temp.h program is written like
#ifndef __temp_h__
#define __temp_h__
.
.
.
#endif

can any one explain what does it mean actually....

Thanks,
kalyan
It's called an include guard. It prevents errors if the header is included multiple times in the same source file.

1
2
3
4
5
6
7
#ifndef __temp_h__  // if '__temp_h__ isn't already defined...
#define __temp_h__  // ...then define it

// .. and compile the stuff in the header

#endif  // if __temp_h__ *was* already defined, the compiler skips to here
//  ie:  it skips over the entire header 


Example:

1
2
3
4
5
6
7
8
// main.cpp

#include "temp.h"  // first time it's #included, so __temp_h__ was not
 // defined yet.  The header will be compiled normally and now __temp_h__ has
 // been defined

#include "temp.h"  // __temp_h__ has already been defined, so this time
 // the header is skipped over 
Thanks Disch..I think I understood now...

so if I have a header file like xxxx.h

inside of xxxx.h i can call it __xxxx_h__

am I correct?



Yes.

You can name the guard whatever you want, just as long as it's unique so that no other header uses the same guard name.
cool Disch, once again thank you...
I also saw another post about this topic in detail
http://www.cplusplus.com/forum/beginner/30180/
Last edited on
Topic archived. No new replies allowed.