Why doesn't the compiler automatically add or generate an include guard by default?

There are times when it is absolutely incorrect to generate the header guard. The standards contain an example: <assert.h> in C and <cassert> in C++.

The effect of reincluding those headers depends on the state of the NDEBUG macro when the header is (re)included. It is legitimate to write:

#undef NDEBUG
#include <assert.h>
…code using assert…
#define NDEBUG 1
#include <assert.h>
…more code using assert…

If the compiler automatically generated a header guard, that would not work correctly. Therefore, compilers do not generate header guards automatically.


Incidentally, user code should not use header guard macro names that start with double underscore, or underscore capital letter. Such names are reserved for the implementation. In C++, no user-defined name may legitimately contain a double underscore at all. Use something more like:

#ifndef A_H_INCLUDED
#define A_H_INCLUDED
…body of header…
#endif