Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) #include guard

 

An #include guard prevents a header file to be compiled multiple times (this will happen if a header file is #included by multiple header files, which will cause a redeclaration error).

 

An #include guard looks like the code below:

 

#ifndef MYHEADERFILE_H
#define MYHEADERFILE_H

//Your header file code, guaranteed to be compiled only once

#endif

 

An implementation (.cpp) file does not have an #include guard, because they do not get #included, but 'Added to Project' instead.

 

Always write internal #include guards [1][2][3]. Never write external #include guards [1]. Use a unique and predictable name [3].

 

 

 

 

 

References

 

  1. Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 24: 'Always write internal #include guards. Never write external #include guards'
  2. Jesse Liberty. Sams teach yourself C++ in 24 hours. ISBN:0-672-32224-2. Hour 21, chapter 'Inclusion and inclusion guards': 'It never hurts to use inclusion guards. Often they will save you hours of debugging time'. Also: hour 24, chapter 'include guards': 'All header files should use inclusion guards'
  3. John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0. Chapter 2.4: 'Place a unique and predicatable (internal) include guard around the contents of each header file'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict