Schi Heil と叫ぶために

hiroakiuno's blog

なぜ gcc はファイルの最後に改行がないと警告を出すのか?

gcc が出す以下の警告。消すのは簡単で EOF に改行を一つ入れれば良い。でもこれ何が悪いのか分からなかった。

warning: no newline at end of file

コンパイラが出す警告だから絶対に何か意味があるはず。調べてみると意外にもテキストファイルの定義にたどり着いた。

ということで POSIX 的に行は改行で終了していて、テキストファイルは行の集合だからファイル末尾には必ず改行が来ると。

Text File / Line - odz buffer

つまり POSIX はテキストファイルにもちゃんと定義を定めていて、最後に改行が無いファイルはその定義に違反するから警告を出す。

There is also some confusion as to whether newlines terminate or separate lines. If a newline is considered a separator, there will be no newline after the last line of a file. The general convention on most systems is to add a newline even after the last line, i.e. to treat newline as a line terminator. Some programs have problems processing the last line of a file if it isn't newline terminated. Conversely, programs that expect newline to be used as a separator will interpret a final newline as starting a new (empty) line. This can result in a different line count being reported for the file, but is generally harmless otherwise.

Newline - Wikipedia, the free encyclopedia

改行を「行と行の separator」と考えるかそれとも「行の terminator」と考えるかはシステムによって分かれるが、一般には POSIX のように terminator と考えるのでファイルの最後には改行が必要だという理屈。

これで警告が出ても自分が悪かったと素直に謝れます。