“文件末尾没有换行符"编译器警告 [英] "No newline at end of file" compiler warning

查看:50
本文介绍了“文件末尾没有换行符"编译器警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些 C++ 编译器中出现以下警告的原因是什么?

What is the reason for the following warning in some C++ compilers?

文件末尾没有换行符

为什么我应该在源文件/头文件的末尾有一个空行?

Why should I have an empty line at the end of a source/header file?

推荐答案

想想如果没有换行可能会出现的一些问题.根据 ANSI 标准,文件开头的 #include 将文件完全按原样插入到文件的前面,并且不会在 #include 之后插入新行.foo.h> 在文件内容之后.因此,如果您在解析器的末尾包含一个没有换行符的文件,它将被视为 foo.h 的最后一行与 foo 的第一行位于同一行.cpp.如果 foo.h 的最后一行是没有新行的注释怎么办?现在 foo.cpp 的第一行被注释掉了.这些只是可能出现的问题类型的几个示例.

Think of some of the problems that can occur if there is no newline. According to the ANSI standard the #include of a file at the beginning inserts the file exactly as it is to the front of the file and does not insert the new line after the #include <foo.h> after the contents of the file. So if you include a file with no newline at the end to the parser it will be viewed as if the last line of foo.h is on the same line as the first line of foo.cpp. What if the last line of foo.h was a comment without a new line? Now the first line of foo.cpp is commented out. These are just a couple of examples of the types of problems that can creep up.

只是想向任何感兴趣的人指出詹姆斯在下面的回答.虽然上述答案对于 C 语言仍然正确,但新的 C++ 标准 (C++11) 已更改,因此如果使用 C++ 和符合 C++11 的编译器,则不应再发出此警告.

Just wanted to point any interested parties to James' answer below. While the above answer is still correct for C, the new C++ standard (C++11) has been changed so that this warning should no longer be issued if using C++ and a compiler conforming to C++11.

来自 C++11 标准,来自 James 的帖子:

From C++11 standard via James' post:

如果源文件不为空且不以换行符结尾,或者在任何此类拼接发生之前以换行符结尾且紧接反斜杠字符结尾,则应将其视为文件中附加了额外的换行符 (C++11 §2.2/1).

A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file (C++11 §2.2/1).

这篇关于“文件末尾没有换行符"编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆