I haven't touched on c++ for a while and this question might be stupid but it indeed bothers me for a while.
Suppose I have the following c program:
#include <stdio.h>
int main()
{
int i;
for(i=0; i<10; i++)
{
printf("Hello World!\n");
}
return 0;
}
I know the reason I include stdio.h
is because I call printf
in main
but I'm wondering how compiler would know where to find the implementation of printf()
during the compilation? stdio.h
only provides function prototype but what exactly is happening during the compilation?
Will there be certain prefixed path that compiler knows to search for the implementation of printf
? If so, how to find them?
Thanks much!
Chances are if you're on a linux system, the C library used is glibc
. GCC doesn't actually provide a C library implementation, only the header files. It's the job of the C library to actually implement the definition of these functions. On Linux, there's something called "shared libraries" which are loaded dynamically by programs that need it. For example:
ldd /usr/bin/gcc
linux-vdso.so.1 (0x00007ffd9e9f8000)
libm.so.6 => /lib64/libm.so.6 (0x00007ff9a35a6000)
libc.so.6 => /lib64/libc.so.6 (0x00007ff9a31de000)
/lib64/ld-linux-x86-64.so.2 (0x000055953c573000)
You can disable the linking of libc
by passing -nostdlib
and link in your own C library. There are also other ways to replace definitions provided by the C library, like linking in your own malloc
and so on. The linker is only allowed to find one definition for any given declaration and since there is no name mangling in C, it's easy to do so.
This is an oversimplified explanation, and doesn't mention builtins, the math library or the like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With