r/C_Programming
•
u/WittyStick
•
Aug 16 '26
•
1
TIL glibc lets you add custom ((v)f)printf format specifiers.
I had a need for an extended printf, and found that rather than writing my own, glibc lets you register your own specifiers with register_printf_specifier.
I made a simple demo for printing bool as it kind of annoys me to have to type printf("%s", value ? "true" : "false"), and I don't like using integers to represent booleans. (This wasn't my goal, but it's the simplest type to demonstrate).
Now can type printf("%?", value) to print true or false. Works will all the *printf style functions.
Has an alt (#) representation, which is uppercase TRUE or FALSE - ie: "%#?".
And I also added width specifiers for easy alignment. You can specify some padding with "%n?" - right aligned by default, with "%-n?" aligning left. Could probably extend to support * also with extra argument for width.
Just thought others may find this interesting.
EDIT : Have been corrected and this also works with *sprintf functions.
9
u/aocregacc Aug 16 '26
why does it not work with *sprintf functions? looks like it works fine when I try it.
3
u/WittyStick Aug 16 '26 edited Aug 16 '26
Should note that it may not be all bells and whistles due to different arguments being in registers or on the stack. My actual use-case doesn't seem to work as intended because there doesn't appear to be any way of getting the argument # in the argsize callback, so we don't know whether it was passed in a register on on the stack, which has consequences for how we extract the arg.
If anyone can figure this out would be very grateful. The type I'm trying to pass is basically a
struct foo { int64_t x; doubly y; }. Under the SYSV convention, this is passed in GP:XMM registers for first few arguments, but later arguments are on the stack. I can get it working for the first 4 arguments, but it starts giving garbage afterwards.My size callback is:
And in the print callback I get it with:
Here's my attempt in godbolt.
I've also tried using a single argument with
PA_POINTERand size 16 - but it also gives garbage.There
argsizecallback appears to get called twice if it returns > 1. I'm not sure what this means or whether it's a bug. Documentation isn't great.36
u/lnemo Aug 16 '26
This is, in fact, interesting. Thank you for sharing.
1
u/vitamin_CPP Aug 16 '26
Do you know how those new specifiers interact with
-Wformat=2and_FORTIFY_SOURCE?2
u/RedWineAndWomen Aug 17 '26
Truly interesting. Thanks!
1
u/reini_urban Aug 17 '26
Whow, didnt knew that. Very useful!
1
u/Physical_Dare8553 Aug 17 '26
This was my inspiration for my gnu constructor based printing system
-10
u/pjl1967 Aug 16 '26
Custom
printfspecifiers just gives you non-portable code.