Page 1 of 1
No Newline at End of File
Posted: Mon Jan 14, 2008 6:10 am
by AJ
Hi,
Just out of interest, does anyone know the reason for the warning above when comiling with gcc? Why would the compiler warn that the last thing in the file has to be a newline - I'm sure there must be some good reason for this!
I'm normally compiling with Solar's huge list of -W flags found in his
Makefile tutorial and this warning is the only one that I find irritating (particularly as I use -Werror) - albeit easily solved
Cheers,
Adam
Posted: Mon Jan 14, 2008 6:22 am
by JamesM
Because the grammar definition will be something like:
Code: Select all
complete_file: NEWLINE
| declaration complete_file
| definition complete_file
;
declaration: TYPE_SPECIFIER STRING
| TYPE_SPECIFIER STRING EQUALS STRING
;
blah blah blah...
Notice that the top rule isn't complete until a NEWLINE has been seen after all definitions/declarations have been parsed. So if you don't end with a newline, all input will have been used up and still the rule complete_file will not have fired! Special code would be nessecary to (possibly) add a newline on to the end of the input stream so that rule fires and the parser exits.
You may ask "Why not add something like this into the lexer?"
Code: Select all
<<EOF>> {yylval="\n";return NEWLINE;}
To answer that: I don't know.
Posted: Mon Jan 14, 2008 6:23 am
by Tyler
I'm not sure about the reasn the warning was added. But it is useful, for example, if you include a file without a new line at the end, and the new line after the include is eaten by the preprocessor to end the include, then the new file will have the next line appended to the end of the last line of the include file. Of course, i'm sure there are no compilers that fall into this trap.
Posted: Mon Jan 14, 2008 7:31 am
by Solar
The reason is quite simple: It's required by the language standard that a non-empty source file shall end with an unescaped newline character. If GCC wouldn't spit a warning on this, it wouldn't be "standard compliant" in that regard.
Posted: Mon Jan 14, 2008 7:47 am
by AJ
Thanks for the replies - perhaps I can be a little less annoyed by the warnings now I have some reasons for it!
Cheers,
Adam