quot;No newline at end of filequot; compiler warning(“文件末尾没有换行符编译器警告)
问题描述
在某些 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).
这篇关于“文件末尾没有换行符"编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“文件末尾没有换行符"编译器警告
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01