编译器忽略 #include 指令是否合法?

编译器忽略 #include 指令是否合法?

问题描述:

据我所知,在编译编译单元时,编译器的预处理器通过扩展 &lt 之间指定的头文件1 的内容来翻译 #include 指令;>(或 ")标记到当前编译单元中.

As I understand, when compiling a compilation unit, the compiler's preprocessor translates #include directives by expanding the contents of the header file1 specified between the < and > (or ") tokens into the current compilation unit.

我的理解是,大多数编译器都支持 #pragma once 指令,以防止由于多次包含同一标头而导致多个定义的符号.遵循 include 守卫习语可以产生相同的效果.

It is also my understanding, that most compilers support the #pragma once directive guarding against multiply defined symbols as a result of multiple inclusion of the same header. The same effect can be produced by following the include guard idiom.

我的问题有两个:

  1. 如果编译器之前遇到过 #pragma once 指令,则完全忽略 #include 指令是否合法或包含保护模式 在这个标题中?
  2. 特别是与 Microsoft 的编译器在这方面是否有任何区别,标头是否包含 #pragma once 指令 或包含保护 模式?文档 建议他们处理相同,尽管有些用户 感觉非常强烈我错了,所以我很困惑,想澄清一下.
  1. Is it legal for a compiler to completely ignore an #include directive if it has previously encountered a #pragma once directive or include guard pattern in this header?
  2. Specifically with Microsoft' compiler is there any difference in this regard whether a header contains a #pragma once directive or an include guard pattern? The documentation suggests that they are handled the same, though some user feels very strongly that I am wrong, so I am confused and want clarification.


1我掩盖了一个事实,即标题不一定是文件 一共.

如果编译器之前遇到过 #pragma once 指令,则完全忽略 #include 指令是否合法或包含保护模式 在这个标题中?

Is it legal for a compiler to completely ignore an #include directive if it has previously encountered a #pragma once directive or include guard pattern in this header?

当然可以!编译器忽略所有源文件和头文件甚至是合法的,只要生成的代码的行为与就好像一样,它处理了所有内容.这就是预编译头文件和目标文件的工作方式——任何没有改变的东西都可以安全地忽略.同样,如果编译器可以证明包含和不包含文件将具有完全相同的行为,则编译器可能会忽略该文件,而不管预处理器指令如何.

Of course it is! It is even legal for the compiler to ignore all your source files and header files so long as behavior of the generated code is the same as if it processed everything. That's how pre-compiled headers and object files work - anything that hasn't changed can be safely ignored. Similarly, if the compiler can prove that including and not including the file are going to have exactly the same behavior, the compiler may ignore the file, regardless of the pre-processor directives.

特别是与 Microsoft 的编译器在这方面是否有任何区别,标头是否包含 #pragma once 指令 或包含保护 模式?

Specifically with Microsoft' compiler is there any difference in this regard whether a header contains a #pragma once directive or an include guard pattern?

文档对此非常清楚.它们是相同的,假设编译器设法识别成语并且您没有 #undef 编辑宏.我也从未遇到任何与此相关的错误.#pragma once 更安全.我有一个实例,其中两个标头具有相同的包含保护和调试,这不是一个很好的体验.

The documentation is pretty clear on that. They are identical assuming the compiler manages to identify the idiom and you haven't #undefed the macro. I've never experienced any bugs related to that either. #pragma once is safer though. I have had an instance where two headers had the same include guard and debugging that wasn't a nice experience.