Why doesn't the compiler add and create an include guard by default?

I know that C or C ++ code usually needs to include the following guards:

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

      

and speed up compile time, in other cpps (ex: B.cpp) it can change

#include "A.h"

      

in

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

      

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

+5


source to share


2 answers


There are times when it is completely wrong to protect the header. The standards contain an example: <assert.h>

in C and <cassert>

in C ++.

The effect of re-including these headers depends on the state of the NDEBUG macro when the header is included (re-enabled). It is permissible to write:

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

      

If the compiler generated the header protection automatically, this will not work correctly. Therefore, compilers do not automatically generate header protections.




By the way, user code should not use header title macro names that start with a double underscore or a capital underscore. Such names are reserved for implementation. In C ++, no user-defined name can contain double underscores. Use something more similar:

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

      

+10


source


The compiler, or more strictly the pre-processor, cannot determine the programmer's intent to use it. The compiler does not explicitly distinguish between .h and .c or .cpp files; they differ only in the type of code in one place. In fact, the compiler only deals with one translation unit; the responsibility of the C preprocessor is to combine all the included files into one file for compilation. It would be wrong for the preprocessor to omit the inclusion it previously included, because it has no semantic knowledge of the code and could lead to a change in intended behavior, guessing the developer.



In some cases, the IDE may add security elements to the template code it generates. For example, Microsoft Visual Studio will add these for the code it generates through its project startup wizards. If this happens at all, it is more the IDE's responsibility than the compiler or preprocessor.

+1


source







All Articles