I write a "hello world" program in C:
void main()
{ printf("Hello World\n"); }
Note that I haven’t included any header file.
The program compiles with warning as
vikram@vikram-Studio-XPS-1645:~$ gcc hello.c
hello.c: In function ‘main’:
hello.c:2:2: warning: incompatible implicit declaration of built-in function ‘printf’
vikram@vikram-Studio-XPS-1645:~$ ./a.out
Hello World
vikram@vikram-Studio-XPS-1645:~$
How is this possible? How does the OS link a library without including any header?
The compiler builds your source file with a reference to a function called
printf(), without knowing what arguments it actually takes or what its return type is. The generated assembly contains apushof the address of the string"Hello World"in the static data area of your program, followed by acalltoprintf.When linking your object file into an executable, the linker sees a reference to
printfand supplies the C standard library functionprintf(). By coincidence, the argument you have passed (const char*) is compatible with the declaration of the realprintf(), so it functions correctly. However, note that theprintf()that your program implicitly declares has return typeint(I think), which the standardprintf()also has; but if they differed, and you were to assign the result of callingprintf()to a variable, you would be in the land of undefined behaviour and you would likely get an incorrect value.Long story short:
#includethe correct headers to get the correct declarations for functions you use, because this kind of implicit declaration is deprecated, because it is error-prone.