__attribute__((format(printf, a, b)))

Recently, looking at libevent source, first saw __attribute __ ((format (printf, a, b))) such an approach. So, here to record usage.

  Function: __ attribute__ format attribute may be declared coupled to the function printf or scanf similar feature, which allows the compiler to check the function declaration and actually invoked if the format string matching between the parameters. The format attribute tells the compiler to check the function of the parameters in accordance with standard C function parameter format rules printf, scanf and so on. This is very useful when debugging interface to package our own information.

  The format syntax is:

format (archetype, string-index, first-to-check)
  wherein, "archetype" specifies what kind of style; "string-index" first specifies several parameters passed to the function is the format string; "first-to- check "specified by the above rules to start checking from the function of several parameters.
Specific use is as follows:
__attribute __ ((the format (the printf, A, B)))
__attribute __ ((the format (Scanf, A, B)))
  where the parameter m and the meaning of n is:
    A: The first several parameters to format strings (the format string);
    B: a first set of parameters, i.e. the parameter "..." in the total number of the first parameter in the first few rows of function parameters.

  Directly to the following example to illustrate:
#include <stdio.h>
#include <stdarg.h>

#if. 1
#define CHECK_FMT (A, B) __attribute __ ((the format (the printf, A, B)))
#else
#define CHECK_FMT (A, B)
#endif

void the TRACE (FMT const char *, ...) CHECK_FMT (. 1, 2);

void the TRACE (FMT const char *, ...)
{
the va_list AP;

the va_start (AP, FMT);

(void) the printf (FMT, AP);

to va_end (AP);
}

int main (void)
{
the TRACE ( "The iValue =% D \ n-",. 6);
the TRACE ( "The iValue =% D \ n-", "Test" );

return 0;
}
  Note: i.e., the need to open warning (-Wall).
  Compile the results are as follows:
main.cpp: the In function 'int main ()':
main.cpp: 26 is: 31 is: warning: the format '% D' the expects argument of type 'int', 2 But argument has type 'const char *' [= -Wformat]
the TRACE ( "The iValue D =% \ n-", " test ");
  if you do not use __attribute__ format there will be no warning.

Guess you like

Origin www.cnblogs.com/qiumingcheng/p/11240278.html