在#include 语句中使用垃圾字符没有编译器错误

No compiler error on using garbage characters in #include statement

#include <iostream> gfhgfhgf
using namespace std;

int main() {
    return 0;
}

为什么这个代码片段可以编译?根据 The gcc reference on Include Syntax:

It is an error if there is anything (other than comments) on the line after the file name.

这正是代码中所做的。

gccclang 中使用 -pedantic-errors 标志将其变成错误 see it live:

error: extra tokens at end of #include directive
#include <iostream> gfhgfhgf
                    ^

表示它是一个扩展。

如果我们查看 Interfacing C and TAL In The Tandem Environment 他们有这样的代码:

#include <stdlibh> nolist
                   ^^^^^^

因此 gccclang 都支持 include 指令后的额外字符,以支持某些平台所需的扩展。使用 -pedantic flags 会使 gccclang 对违反标准的扩展产生警告,如上所述,您可以使用 -pendatic-errors 将其变成错误(强调我的):

to obtain all the diagnostics required by the standard, you should also specify -pedantic (or -pedantic-errors if you want them to be errors rather than warnings).

我们可以在 HP'sC/C++ Programmers guide for NonStop Systrms 中找到 nolist 扩展名的参考,上面写着:

nolist
  directs the compiler not to list the contents of the file or sections
  being included.
This is an HP NonStop  extension to the standard.

注意,draft C++ standard16.2 [cpp.include] 部分将这种形式的 include 的语法定义为如下:

# include < h-char-sequence> new-line