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?
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?
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.
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 aMyHeader.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.The requirement that every source file end with a non-escaped newline was removed in C++11. The specification now reads:
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).
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.
#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.