“No newline at end of file” compiler warning

后端 未结 11 937
逝去的感伤
逝去的感伤 2020-11-27 09:50

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

相关标签:
11条回答
  • 2020-11-27 10:36

    Because the behavior differs between C/C++ versions if file does not end with new-line. Especially nasty is older C++-versions, fx in C++ 03 the standard says (translation phases):

    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, the behavior is undefined.

    Undefined behavior is bad: a standard conforming compiler could do more or less what it wants here (insert malicous code or whatever) - clearly a reason for warning.

    While the situation is better in C++11 it is a good idea to avoid situations where the behavior is undefined in earlier versions. The C++03 specification is worse than C99 which outright prohibits such files (behavior is then defined).

    0 讨论(0)
  • 2020-11-27 10:38

    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.

    0 讨论(0)
  • 2020-11-27 10:39

    I am using c-free IDE version 5.0,in my progrm either of 'c++' or 'c' language i was getting same problem.Just at the end of the program i.e. last line of the program(after braces of function it may be main or any function),press enter-line no. will be increased by 1.then execute the same program,it will run without error.

    0 讨论(0)
  • 2020-11-27 10:47

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

    0 讨论(0)
  • 2020-11-27 10:48

    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.

    0 讨论(0)
提交回复
热议问题