1

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

3

1 Answer 1

2

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'.

2
  • So you need a system call to move things to stdout. Is it possible that in UNIX-like OSes stdout can be written through a file descriptor? Commented Oct 9, 2011 at 11:01
  • @Fabian Yes you can write through a file descriptor, but that's a system call anyway. Normally I'd use a C support library for this, regardless of the language it's implementing. You can spit it out as ASM - off the top of my head for Linux x86 you put 4 (sys_write) in EAX, the file descriptor (1 for stdout) in EBX, a data pointer in ECX and a length in EDX and then use int 80h to make the call. Linking against a runtime support library for this is far nicer though. Commented Oct 9, 2011 at 11:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.