开发者

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 progra开发者_运维问答m you call into libc and that's it. But how does the printf() stuff work internally?

Cheers


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜