Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where the compiler find ``printf``?

Tags:

c++

c

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!

like image 860
xxks-kkk Avatar asked Dec 19 '22 17:12

xxks-kkk


1 Answers

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.

like image 160
user6318521 Avatar answered Dec 24 '22 01:12

user6318521