How to implement stdarg in C

前端 未结 4 1335
無奈伤痛
無奈伤痛 2020-12-21 00:43

For curiosity, I\'m looking to write minimal replacements for some of the functions in the standard C library. So far, I have finished printf(), strlen()<

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 01:27

    There is no way to implement stdarg.h macros in C; you need compiler builtins like __builtin_va_arg, etc. which GCC and compatible compilers provide, or the equivalent for your compiler.

    Even if you know the argument passing convention for the particular target you're working with (like i386 in icktoofay's answer), there is no way in C to get access to this memory. Simply performing pointer arithmetic on the address passed to va_start is not valid; it results in undefined behavior. But even if C did allow that arithmetic, there's no guarantee that the address of the last named argument actually corresponds to the place it was passed on the stack as part of the calling convention; the compiler could have chosen to move it to a different location in its stack frame (perhaps for the sake of obtaining additional alignment or data locality).

提交回复
热议问题