A couple of years ago, I wanted to put some functions to write logs into a C library (shared object). My idea was to have something that was easy to use in every situation. Since, most of the times, variables must be printed, I decided to create a function with a variable number of arguments, just like
It has been quite simple, by using the functions declared in
vfprintf(). But there was something that I was missing: the check for the correctness of the parameters.
This is something that GCC automatically does for every printf-like function. At compile time, it verifies if the type of the arguments matches what's specified in the format string and it notifies every mismatch with a warning.
So I told myself that there should be a way and, after a little search, I found the
format (archetype, string-index, first-to-check)
The format attribute specifies that a function takes
strfmonstyle arguments that should be type-checked against a format string. For example, the declaration:
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
causes the compiler to check the arguments in calls to
my_printffor consistency with the
printfstyle format string argument my_format.
With a simple specification in the declaration of the function it's now possible to be warned when parameters don't match format string.
At this page there are many other attributes. Many of them can be used to improve the compiler optimizations, by telling it something about the usage of some of the functions that compose your program.
Cover image by Sucheta Ghoshal taken from Wikimedia Commons licensed under the Creative Commons Attribution-Share Alike 4.0 International license.