3

How this following code can run without including header file for printf function?

int main(){
printf("%d",1);
return 0;}
lurker
  • 56,987
  • 9
  • 69
  • 103
Govinda Raj
  • 55
  • 10

1 Answers1

3

Note: This is a hand-wavy answer that will roughly be correct. Someone else who knows the gory details (for gcc, e.g.) may enlighten both of us. Here goes:

Because in C — at least for some compilers — implicitly defined functions are fine. So it compiles it, then hands it off to the linker. It sees a reference to printf, and since the linker by default links with the C runtime library, it will resolve that symbol to the correct function.

I guess an implicit function like that will get a default signature, typically expecting to return an int. As for the arguments to the function, those can't be type checked at compile time, because the compiler doesn't know what the actual function signature is. So it will just use standard calling convention, e.g. pass arguments by registers or something like that.

csl
  • 10,937
  • 5
  • 57
  • 89
  • 1
    what standards? Its not in C99 anyway and would constitute an error. – t0mm13b Jun 27 '17 at 22:17
  • OK, I guess it should say "some compilers" then. Thanks – csl Jun 27 '17 at 22:19
  • 2
    Technically, calling a varags function like `printf()` without a prototype in scope was undefined behaviour even in C90. In practice, you usually got away with it, but it was never standards conforming. Change the function from `printf()` to `puts()`, for example, and it was OK in C90, though not recommended. – Jonathan Leffler Jun 28 '17 at 00:37