• 12
• 10
• 10
• 13
• 10

# What are 'inclusion guards'?

This topic is 4863 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

See subject, what are they and why are they needed. They're not covered in any of my C++ books.

##### Share on other sites
Inclusion guards are those #ifndef BLAHBLAH #define BLAHBLAH things at the top of a header file and the #endif at the bottom. They prevent a header file from being included multiple times. Sometimes a header file will include another header file, and if you include both of those in your code it'll include one of them twice (because it was included by you and included by a header you included). Inclusion guards prevent multiple definitions and declarations by defining something and checking it to see whether or not to include the code.

// myheader.h#ifndef __MY_HEADER__#define __MY_HEADER__class blahblahblah{// ...};#endif// otherheader.h#include "myheader.h"// main.cpp#include "myheader.h"#include "otherheader.h"// "class blahblahblah" is only seen by the compiler once

##### Share on other sites
With Visual C++, you could use "#pragma once" to tell the preprocessor that you'd like to use the current file only once for inclusion. However, the said pragma is not very portable at all.

I recommend using the method that Ra presents.

##### Share on other sites
@Ra. Oh I get it! So if you include two header files but one includes the other, you get a much less disturbing error (and not 400 errors of redefinitions), because you've redefined a define.
Thanks!

##### Share on other sites
Quote:
 Original post by Drakkcon@Ra. Oh I get it! So if you include two header files but one includes the other, you get a much less disturbing error (and not 400 errors of redefinitions), because you've redefined a define.Thanks!
Not quite. The #ifndef checks whether it's defined so it doesn't include any of the code twice. A header file included twice with inclusion guards will silently compile and produce no errors while preventing its code from being included twice.