Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why GCC doesn't generate any warnings about newline at end of file?

Tags:

c

newline

gcc

clang

From C11 5.1.1.2 Translation phases:

Paragraph 2:

[...] A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.

It means every source file must end with a newline.

Example:

#include <stdio.h>

int main() 
{
    printf("Hello world\n");
    return 0;
}

Above example compiled on Clang using clang prog.c -Wall -Wextra -std=gnu11 -pedantic command. The compiler generates following warning:

prog.c:7:16: warning: no newline at end of file [-Wnewline-eof]
}
               ^

It's ok because there is no newline at the end of the source file.

Using gcc prog.c -Wall -Wextra -std=gnu11 -pedantic command, I compiled the above program on GCC. GCC doesn't generate any warning or error.

So, Why doesn't GCC generate any warning or error?

  1. Clang Live Demo

  2. GCC Live Demo

like image 560
msc Avatar asked Mar 07 '23 13:03

msc


1 Answers

The meaning of "shall" is defined by section 4 point 2:

If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined.

The passage you quoted is not in a Constraints section. Therefore, if the source file does not end in a trailing newline then the program has undefined behaviour.

No diagnostic is required for undefined behaviour. The compiler is free to do anything. The GCC developers have probably decided to make the program behave as if there were a newline on the end and not bother the user with a warning.

like image 58
M.M Avatar answered Apr 25 '23 03:04

M.M