about including header files
Andrew Haley
aph@redhat.com
Tue Nov 10 15:14:00 GMT 2009
Axel Freyn wrote:
> On Tue, Nov 10, 2009 at 11:07:31AM +0000, Andrew Haley wrote:
>> yacson wrote:
>>> Hi everybody.
>>> what happens if a "header include" is missing? because I unexpectedly notice
>>> that this code:
>>> main()
>>> {printf("hello");}
>>>
>>> works in linux(at least on my (mandriva spring 2007 )box) while it does not
>>> in windows(turbo C++).
>>> so finally, can I say : #include <stdio.h> is not always necessary!
>> Strictly speaking, I think this is undefined behaviour. So, while it
>> might work, it's not correct code, and it may break at any time.
> I think this are two questions mixed up:
> a) in this example, the function "printf" is not explicitely defined.
> And implicit function declaration were allowed in the C 89, but
> aren't permitted in C 99. So you have to decide which version of the
> C standard you are writing in:-)
> But according to my understanding of the standard, even looking at
> C89, the behaviour of your code is undefined, as implicit function
> declaration is only allowed for functions having a fixed number of
> parameters - and that's not the case for printf.
> So I would say:
> - for C99: it is wrong, the compiler should not translate the code.
That's not quite true. The compiler must issue a diagnostic, but whether
or not it translates the code is up to the compiler.
Note that gcc does issue a diagnostic:
ped.c:2: warning: incompatible implicit declaration of built-in function 'printf'
> - for C89: the behaviour is undefined, the compiler can do what he
> wants :-)
>
> b) The second question is: do you need to include stdio.h in order to
> declare printf - or is it sufficient to declare printf yourself?
> According to §7.1.4.2, it's not necessary to include stdio.h: If
> it is possible to declare a function from the standard library
> without using a type defined in a header, it is "permissible" to
> declare the function an use it - witout including the standard
> header: "printf" beeing declared as
> int printf(const char * restrict format, ...);
> it is sufficient to declare "printf" in your source code.
>
> So, in my opinion, the code
>
> int printf(const char * format, ...);
> main()
> {printf("hello"); }
>
> should be perfectly valid and work with all C89 or C99 compilers -
> without the inclusion of stdio.h ?
Yes.
Andrew.
More information about the Gcc-help
mailing list