Jump to content
  • Advertisement
Sign in to follow this  
Drakkcon

What are 'inclusion guards'?

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

Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!