What type of behaviour is this?-Collection of common programming errors
This question is looking for a standardese quote explicitly explaining why this behavior is wrong.
The code below including inside main
,
int main()
{
#include
printf("hello , world \n");
return 0;
}
On gcc -Wall in.c -o in.out
It successfully compiles and prints hello , world
.
But on clang in.c -o in.out
It gives me this error :
/usr/include/stdio.h:353:12: error: implicit declaration of 'fprintf' requires
inclusion of the header
extern int fprintf (FILE *__restrict __stream,
^
1 error generated.
My doubt is what kind of behaviour is this ? Is this undefined behaviour or what ?
Also I am not able to find the documentation related to it.
EDIT : The problem is that I found this code somewhere similar to it but I can’t post that code exactly so I posted this kind of Demo code.I know the Placing stdio.h
outside the main.
-
C99, 7.1.2/4:
[…] If used, a header shall be included outside of any external declaration or definition, and it shall first be included before the first reference to any of the functions or objects it declares, or to any of the types or macros it defines.
4/2:
If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the behavior is undefined.
6.9/4:
As discussed in 5.1.1.1, the unit of program text after preprocessing is a translation unit, which consists of a sequence of external declarations. These are described as ‘‘external’’ because they appear outside any function (and hence have file scope).
So I think this is undefined behavior.
-
In C++11: 17.6.2.2/3:
A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header.
main()
is extern, so is not a proper context for include. -
Try including the header file outside of the main method. Like this.
#include int main() { printf("hello , world \n"); return 0; }
Originally posted 2013-11-09 23:18:10.