I came across this line of code in a C project, and I did not understand it.
#define FMT_CHK(fmt, args) __attribute__ ((format (printf, fmt, args)))
The GNU website does not explain it clearly (https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes)
What is the purpose of __attribute__ ((format ())
and how should it be used?
The __attribute__ is added just after the variable name, and though it can appear unwieldy, it's a style you can get used to: int main(int argc __attribute__((unused)), char **argv) { ...
__attribute__((section("name"))) variable attribute data and . bss . However, you might require additional data sections or you might want a variable to appear in a special section, for example, to map to special hardware. The section attribute specifies that a variable must be placed in a particular data section.
Attributes are a mechanism by which the developer can attach extra information to language entities with a generalized syntax, instead of introducing new syntactic constructs or keywords for each feature.
So, the fmt
and args
parameters just tell you which parameter has the format, and which parameter has the arguments.
void myprintf(const char *fmt, ...);
// ^^ fmt = arg#1
// ^^ args = arg#2...
So in this case, the correct attribute is:
__attribute__((format(printf, 1, 2)))
If you have a longer function declaration...
void myprintf(obj *x, const char *fmt, int level, ...)
// ^^ format: arg#2
// ^^ args: arg#4...
__attribute__((format(printf, 2, 4)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With