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 a push
of the address of the string "Hello World"
in the static data area of your program, followed by a call
to printf
.
When linking your object file into an executable, the linker sees a reference to printf
and supplies the C standard library function printf()
. By coincidence, the argument you have passed (const char*
) is compatible with the declaration of the real printf()
, so it functions correctly. However, note that the printf()
that your program implicitly declares has return type int
(I think), which the standard printf()
also has; but if they differed, and you were to assign the result of calling printf()
to a variable, you would be in the land of undefined behaviour and you would likely get an incorrect value.
Long story short: #include
the correct headers to get the correct declarations for functions you use, because this kind of implicit declaration is deprecated, because it is error-prone.