“No newline at end of file” compiler warning

2019-01-05 08:25发布

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

No newline at end of file

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

11条回答
ら.Afraid
2楼-- · 2019-01-05 08:57

It isn't referring to a blank line, it's whether the last line (which can have content in it) is terminated with a newline.

Most text editors will put a newline at the end of the last line of a file, so if the last line doesn't have one, there is a risk that the file has been truncated. However, there are valid reasons why you might not want the newline so it is only a warning, not an error.

查看更多
仙女界的扛把子
3楼-- · 2019-01-05 09:04

Of course in practice every compiler adds a new line after the #include. Thankfully. – @mxcl

not specific C/C++ but a C dialect: when using the GL_ARB_shading_language_include extension the glsl compiler on OS X warns you NOT about a missing newline. So you can write a MyHeader.h file with a header guard which ends with #endif // __MY_HEADER_H__ and you will lose the line after the #include "MyHeader.h" for sure.

查看更多
迷人小祖宗
4楼-- · 2019-01-05 09:04

The requirement that every source file end with a non-escaped newline was removed in C++11. The specification now reads:

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).

A conforming compiler should no longer issue this warning (at least not when compiling in C++11 mode, if the compiler has modes for different revisions of the language specification).

查看更多
聊天终结者
5楼-- · 2019-01-05 09:09

The answer for the "obedient" is "because the C++03 Standard says the behavior of a program not ending in newline is undefined" (paraphrased).

The answer for the curious is here: http://gcc.gnu.org/ml/gcc/2001-07/msg01120.html.

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-05 09:10

#include will replace its line with the literal contents of the file. If the file does not end with a newline, the line containing the #include that pulled it in will merge with the next line.

查看更多
登录 后发表回答