Tom
Tom

Reputation: 1394

Does gcc include some header files automatically?

I have the following code:

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

I compiled it using the following command:

gcc -o myprogram myfile.c

And it compiled without any error even though I did not #include <stdio.h>. So did gcc include this header file automatically?

My gcc version is 4.3.3

Upvotes: 3

Views: 2109

Answers (2)

Elmar Peise
Elmar Peise

Reputation: 15413

No, gcc did not include any header files you didn't request. #include statements are C preprocessor macros (like #define or #if) that are actually evaluated before the actual C compilation. You can see what your code looks like after all macros are resolved by calling gcc -E myfile.c. As you will see, printf will still not be declared.

If you compile with -Wall, you should get a warning that printf is undeclared. However gcc "guesses" how printf is used (probably from its arguments, but it could also simply know the routine internally). Since it finds a matching symbol name while linking, you don't get an error and your program runs just fine.

BTW, gcc 5.3.0 shows the following warning:

myfile.c: In function 'main':
myfile.c:3:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
     printf("Hello\n");
     ^
myfile.c:3:5: warning: incompatible implicit declaration of built-in function 'printf'
myfile.c:3:5: note: include '<stdio.h>' or provide a declaration of 'printf'

Upvotes: 1

fuz
fuz

Reputation: 93024

In ANSI C, you can call functions you didn't declare. Such functions are implicitly declared the first time you call them. They are assumed to return int and take arguments according to the default argument promotions. Since you didn't include <stdio.h>, the compiler uses this rule and implicitly declares printf. Note that this is undefined behaviour as functions that take variable argument lists like printf must be declared explicitly. gcc usually warns you if it uses the implicit declaration rule since it's usually not intentionally used.

Upvotes: 3

Related Questions