static void ddict_debug(const char* fmt, ...) G_GNUC_PRINTF(1, 2);
我在一个.c文件中发现了这行代码,但不理解它的含义:
是只有一个函数声明还是两个?
这段代码是什么意思?
G_GNUC_PRINTF()
是一个 glib 库的预处理宏。对于 gcc 编译器,它被定义为以下内容(来自 glib-2.4.5/glib/gmacros.h
):
#define G_GNUC_PRINTF( format_idx, arg_idx ) \
__attribute__((__format__ (__printf__, format_idx, arg_idx)))
format_idx
:对应于格式字符串的参数的索引(参数从1开始编号)
arg_idx
:格式参数的第一个参数的索引static void ddict_debug(const char* fmt, ...) G_GNUC_PRINTF(1, 2);
// | | | |
// format string, format_idx = 1 ----+ | <----+ |
// format arguments, arg_idx = 2 ---------+ <-------+
示例2:
static void foo_debug(int foo, const char* fmt, ...) G_GNUC_PRINTF(2, 3);
// | | | | |
// not a printf argument --+ | | | |
// format string, format_idx = 2 -----------+ | <----+ |
// format arguments, arg_idx = 3 ----------------+ <-------+
摘要:
这里只有一个函数声明还是两个?
这里定义了一个类似printf()的函数。该宏告诉编译器对传递给函数的参数进行类型检查。
static void ddict_debug(const char* fmt, ...);
,“G_GNUC_PRINTF(1, 2)
”部分可能是一个宏,它会扩展为特定于编译器的函数注释。例如,gcc使用它来验证类似于printf
函数的参数,此时它会扩展为__attribute__ ((format (printf, 1, 2)));
有关更多详细信息,请参阅:
https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes