您的位置:首页 > 其它

__attribute__ format

2015-09-22 13:42 267 查看
This __attribute__ allows assigning printf-like or
scanf-like characteristics to the declared function, and this enables the compiler to check the format string against the parameters provided throughout the code. This is
exceptionally helpful in tracking down hard-to-find bugs.

There are two flavors:

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

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

but in practice we use the first one much more often.

The (m) is the number of the "format string" parameter, and (n) is the number of the first variadic parameter. To see some examples:

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

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

With the functions so declared, the compiler will examine the argument lists

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

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

Note that the "standard" library functions - printf and the like - are already understood by the compiler by default.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: