C language attribute

www‮.‬lautturi.com
C language attribute

attribute

out(int level, const char *file, int line, const char *function, pthread_t tid, const char *fmt, ...) __attribute__ ((format (printf, 7, 8)));

What does this mean: __attribute__ ((format (printf, 7, 8)));

__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))

The meanings of parameters m and n are as follows:
m: format string as the first parameter.
n: indicates the first parameter in the parameter set, that is, parameter "... ". Is the first parameter in the function parameter list

This tells the compiler that our code are using with printf scanf, and it tells compiler which parameter is a format string, which parameter is a parameter list,

/* like printf() but to standard error only */
extern void eprintf(const char *format, ...)
   __attribute__((format(printf, 1, 2)));  /* 1=format 2=params */

/* printf only if debugging is at the desired level */
extern void dprintf(int dlevel, const char *format, ...)
   __attribute__((format(printf, 2, 3)));  /* 2=format 3=params */

This feature is useful, especially for bugs that are hard to find.

$ cat test.c
1  extern void eprintf(const char *format, ...)
2               __attribute__((format(printf, 1, 2)));
3
4  void foo()
5  {
6      eprintf("s=%s\n", 5);             /* error on this line */
7
8      eprintf("n=%d,%d,%d\n", 1, 2);    /* error on this line */
9  }

$ cc -Wall -c test.c
test.c: In function `foo':
test.c:6: warning: format argument is not a pointer (arg 2)
test.c:8: warning: too few arguments for format

another example is

1: extern void myprint(const char *format,...) __attribute__((format(printf,1,2)));
2: void test()
3: {
4:      myprint("i=%d\n",6);  OK
5:      myprint("i=%s\n",6);  Error 
6:      myprint("i=%s\n","abc"); OK
7:      myprint("%s,%d,%d\n",1,2); Error
8: }

$gcc -Wall -c attribute.c attribute
attribute.c: In function `test':
attribute.c:5: warning: format argument is not a pointer (arg 2) You can see a warning while compiling .
attribute.c:7: warning: format argument is not a pointer (arg 2)
attribute.c:7: warning: too few arguments for format

In lots of open source codes , you can see the code like this.

Created Time:2017-08-22 14:43:39  Author:lautturi