Fabian Schuiki
Fabian Schuiki

Reputation: 1308

Implementation of a printf() function

I'm working ona toy programming language. I use LLVM to generate machine code. Now my question is: How do you implement a printf() function from scratch?. In a C program you call into libc and that's it. But how does the printf() stuff work internally?

Cheers

Upvotes: 1

Views: 2065

Answers (1)

There are two parts to a printf() implementation.

Firstly you have some mechanics for your particular calling convention that make variadic arguments possible.

Secondly though you write a loop that looks through the format specifier given to the function. In simplistic terms it takes one of two actions, either copies the string to stdout (via an appropriate system call for your platform) or takes one of the variadic arguments passed to the function and displays that appropriately (again using a system call for the output) for the format that was specified.

For example if you see a %s then you need to retrieve the next unconsumed argument, interpret it as a char * pointer and then ensure that the memory it points to gets copied to stdout until you hit '\0'.

Upvotes: 2

Related Questions