67
votes

Possible Duplicate:
source code of c/c++ functions

I was wondering where I can find the C code that's used so that when I write printf("Hello World!"); in my C programm to know that it has to print that string to STDOUT. I looked in <stdio.h>, but there I could only find its prototype int printf(const char *format, ...), but not how it looks like internally.

1
I don't think there's the source available. +1 anyway, I always wondered this. - BlackBear
printf is defined in terms of putc so there's no need for it to make any OS calls. - R.. GitHub STOP HELPING ICE
@Tergiver, @R: You're both right. printf handles formatting, then calls putc, which may call other helper functions but ultimately results in an OS call. - Ben Voigt
My point was that the OS calls are at a much lower level, and printf is essentially a pure library function on top of lower-level stdio calls. - R.. GitHub STOP HELPING ICE

1 Answers

94
votes

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)