I'm currently writing a C standard library for academic purposes, and I wondered how to implement stdarg.h (the va_* macros) in C (probably with inline ASM) and if this was the libc's work, or the compiler's ?
Thanks in advance.
Varargs are part of the C language syntax, not the standard library. If you're implementing them in a header, you're doing it wrong.
Name:
Anonymous2012-09-06 2:11
>>1
It depends on the C ABI of the target platform, and how arguments are passed in memory on the stack to a function.
The va_* macros are usually implemented in terms of pointer arithmetic... simply incrementing/decrementing to the next machine-word sized location on the stack.
Name:
Anonymous2012-09-06 2:18
Sometime ago I wrote a simple OS and it just used macros from stdarg.h
Find out how long the number will be, and fill the buffer backwards from there. Simple and efficient.
It's more likely he did that because "reverse a string in place" is one of those "clever interview questions" that have very little use in practice and he just wanted to show it off.
Name:
Anonymous2012-09-07 4:13
Variadic functions complicate type checking and optimisation. Abandon and replace them with more efficient meta-programming-based techniques.
For instance, you can have a preprocessor turn printf("%02x: %s\n", i, strings[i]); into print_hex(2, i); print_string(": "); print_string(strings[i]);.
>>12
I doubt that is more efficient especially as the format string becomes more complicated. 5 bytes per call, not including all the extra parameters passed.
Name:
Anonymous2012-09-07 11:28
So, the compiler takes care of this ?
Great then, thank everybody.
Also, this will be for x86-64 only.
Name:
Anonymous2012-09-07 13:03
>>12
I'm not convinced that is even true in general, but at least for printf the time it takes to create the printable string from the format and parameters is trivial compared to the time it takes to output the buffer. So even if you changed it to be only one syscall as in
char line[LINE_LEN];
sprintf(line, "%2x", i); // your specific hex-to-string function here
strncpy(line + 2, ": ", 2);
strcpy(line + 4, strings[i]);
puts(line);
you wouldn't gain much. When is printf a bottle-neck anyway? Could you as easily chop another variadic function into separate functions?
Name:
Anonymous2012-09-07 13:59
>>16
>strncpy(line + 2, ...)
I think you mean "strcat".
Name:
Anonymous2012-09-07 14:41
Could-er, what is the best way for a human with little to no knowledge of programming to learn programming?
Before you say that, that must be implementation specific, consider the case of the average person.