Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know C or C++ code usually needs to use include guards like this:

#ifndef __A__H__
#define __A__H__
class A{
};
#endif

and to speed up compile time, in other cpp (e.g.:B.cpp), it can change

#include "A.h"

to:

#ifndef __A__H__
#include "A.h"
#endif

but the question is why doesn't the compiler automatically add or generate the include guard, and therefore why does the programmer need to add it manually if an include guard is usually required?

like image 443
ggrr Avatar asked Aug 10 '15 04:08

ggrr


2 Answers

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
like image 197
Jonathan Leffler Avatar answered Oct 09 '22 10:10

Jonathan Leffler


The compiler, or more strictly the pre-processor cannot determine the programmer's intent in using inclusion. The compiler does not explicitly distinguish between .h files and .c or .cpp files; they differ only in the type of code one places in them. In fact the compiler deals only in a single translation unit; it is the responsibility of the C preprocessor to concatenate all included files into a single file for compilation. It would be incorrect for the pre-processor to omit an inclusion that it has previously included because it has no semantic knowledge of the code and may cause intended behaviour to change by second-guessing the developer.

In some circumstances, an IDE may add include guards for template code that it has generated. For example Microsoft Visual Studio will add them for code that it generates via its project start-up wizards. If it happens at all, it is properly the responsibility of the IDE rather than the compiler or pre-processor.

like image 1
Clifford Avatar answered Oct 09 '22 12:10

Clifford