Abhiraj Darshankar
Abhiraj Darshankar

Reputation: 97

Printf is not a part of c language. What actually happens when following PRINTF's code is executed from stdio.h?

int printf (const char *__format, ...)
{
  register int __retval;
  __builtin_va_list __local_argv; __builtin_va_start( __local_argv, __format );
  __retval = __mingw_vprintf( __format, __local_argv );
  __builtin_va_end( __local_argv );
  return __retval;
}

above lines are part of stdio library corresponding to printf function. when printf is called these are executed. What do these line mean? what happens when each of the above lines are executed?

Upvotes: 2

Views: 2368

Answers (1)

luser droog
luser droog

Reputation: 19504

This is mostly a wrapper for another function __mingw_vprintf which does the real work. The only code here is repackaging the variable-argument list. So to really see how Mingw does it, you'll have to look at that function and any other functions it calls. If you're really interested in this, you should get a copy of P.J. Plauger's The Standard C Library. He tells you how to use, write, and test every function in the standard library.

Library code in general is compiled into object files (just like your code is), and then packaged in an archive format. When your program is linked, the library objects needed are extracted from the archive and written into the same executable. This is for a statically-linked library.

For a dynamically-linked library, the library code archive is loaded as a whole into memory (and usually shared by any programs which need to use it), and your program makes library-calls with the help of the operating system to facilitate the memory-sharing.

For both types of libraries, the header files should only contain macros, types, and function prototypes. It should not contain any function definitions (those belong in .c files).

Here's an ancient version of printf from before the existence of the standard library: link (<-- This one's actually readable(ish)). Curiously, the 7th-edition version looks a lot like the one you quote above:

#include    <stdio.h>

printf(fmt, args)
char *fmt;
{
    _doprnt(fmt, &args, stdout);
    return(ferror(stdout)? EOF: 0);
}

In this case, _doprnt is implemented in assembly language.

Upvotes: 5

Related Questions