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

No compiler error on using garbage characters in #include statement

本文关键字:编译器 #include 错误 字符 语句      更新时间:2023-10-16
#include <iostream> gfhgfhgf
using namespace std;
int main() {
    return 0;
}

为什么要编译此代码片段?根据 gcc 参考 包含语法:

如果文件名后面的行上有任何内容(注释除外),则为错误。

这正是代码中所做的。

gcc 中使用 -pedantic-errors 标志,clang将其变成错误 实时查看:

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

表示它是一个扩展。

如果我们看一下串联环境中的接口C和TAL,它们有一些这样的代码:

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

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

获得标准要求的所有诊断,您应该 还要指定 -pedantic(或 -pedantic-errors ,如果你希望它们是 错误而不是警告)。

我们可以在 HP'sC/C++ 程序员指南中找到 nolist NonStop 系统扩展的参考,其中说:

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.

请注意,C++标准草案在第 16.2 节 [cpp.include] 中定义了这种include形式的语法,如下所示:

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