"No newline at end of file" compiler warning
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?
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.
Edit : 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 C++11 conformant compiler.
From C++11 standard via James' post:
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).
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).
C++03 Standard [2.1.1.2] declares:
... If a source file that is not empty does not end in a new-line character, or ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, the behavior is undefined.
链接地址: http://www.djcxy.com/p/77238.html上一篇: VIM在文件结束时禁用自动换行
下一篇: “文件末尾没有换行符”编译器警告