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

前端 未结 2 713
刺人心
刺人心 2021-01-12 21:17

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 co

2条回答
  •  鱼传尺愫
    2021-01-12 22:06

    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.

提交回复
热议问题