c - 为什么 GCC 不在文件末尾生成任何关于换行符的警告?

标签 c gcc clang newline

来自 C11 5.1.1.2 翻译阶段:

第 2 段:

[...] A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.

这意味着每个源文件都必须以换行符结尾。

例子:

#include <stdio.h>

int main() 
{
    printf("Hello world\n");
    return 0;
}

以上示例使用 clang prog.c -Wall -Wextra -std=gnu11 -pedantic 命令在 Clang 上编译。编译器生成以下警告:

prog.c:7:16: warning: no newline at end of file [-Wnewline-eof]
}
               ^

没关系,因为源文件末尾没有换行。

使用 gcc prog.c -Wall -Wextra -std=gnu11 -pedantic 命令,我在 GCC 上编译了上面的程序。 GCC 不会生成任何警告或错误。

那么,为什么 GCC 不生成任何警告或错误?

  1. Clang Live Demo

  2. GCC Live Demo

最佳答案

“应”的含义由第 4 节第 2 点定义:

If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined.

您引用的段落不在约束部分。因此,如果源文件不以尾随换行符结尾,则程序具有未定义的行为。

对于未定义的行为不需要诊断。编译器可以自由地做任何事情。 GCC 开发人员可能已经决定让程序的行为就像末尾有一个换行符一样,而不是用警告来打扰用户。

关于c - 为什么 GCC 不在文件末尾生成任何关于换行符的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47410876/

相关文章:

c - 如何检测客户端内部的pclose

c - GCC C vector 扩展 : How to test the result of a comparison (for conditional assignment, 等)?

gcc - 如何在 ubuntu 上安装新版本的 gcc

c - gcc -O3 问题,从不同的文件调用相同的函数会产生不同的性能

c++ - clang - 符号(变量、函数、类型等)定义或声明或引用

c - 如何在没有任何附加参数的情况下获取函数中的数组大小

c - 对学生数据库进行散列(使用链)(位折叠/加法散列)

c++ - 我可以使用 LLVM 来加速构建并减少 GCC 编译时间吗?

python - 如何配置环境以使用 LLVM Clang 构建 python 嵌入式 c 代码

c - C是否支持 union 的匿名成员?