Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ header guards around object and usage?

I am used to putting header guards around my objects like:

#ifndef SOMETHING_H
#define SOMETHING_H

class Something {
...
}
#endif

but I have been given code where they also do:

#ifndef SOMETHING_H
#include "something.h"
#endif

for every include. Supposedly, this is better. Why? Is this redundant with guards around the object?

like image 948
Chad Befus Avatar asked Nov 06 '13 00:11

Chad Befus


1 Answers

This is discussed in pretty good detail here:
http://c2.com/cgi/wiki?RedundantIncludeGuards

Here are the highlights:

  • Yes this is redundant, but for some compilers it may be faster because the compiler will avoid opening the header file if it doesn't need to.
  • "Good compilers make this idiom unnecessary. They notice the header is using the include-guard idiom (that is, that all non-comment code in the file is bracketed with the #ifndef). They store an internal table of header files and guard macros. Before opening any file they check the current value of the guard and then skip the entire file."
  • "Redundant guards have several drawbacks. They make include sections significantly harder to read. They are, well, redundant. They leak the guard name, which should be a secret implementation detail of the header. If, for example, someone renames the guard they might forget to update all the places where the guard name is assumed. Finally, they go wrong if anyone adds code outside of the guard. And of course, they are just a compile-time efficiency hack. Use only when all else fails."
like image 125
Andrew Clark Avatar answered Sep 19 '22 22:09

Andrew Clark