Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of __attribute__ (format) in C to define a function?

Tags:

c

gcc

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?

like image 861
sbhatla Avatar asked Feb 08 '16 21:02

sbhatla


People also ask

Where is __ attribute __ defined?

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) { ...

What is __ attribute __ (( section?

__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.

What is attribute in C language?

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.


1 Answers

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)));
like image 67
Dietrich Epp Avatar answered Sep 20 '22 10:09

Dietrich Epp