gpt4 book ai didi

c - 这个通用函数有什么作用?

转载 作者:太空狗 更新时间:2023-10-29 17:00:40 25 4
gpt4 key购买 nike

static inline __printf(2, 3)
int dev_err(const struct device *dev, const char *fmt, ...)
{ return 0; }

__printf() 在做什么,dev_err 的第三个 arg(...) 是什么意思?我可以想象这个函数是某种通用函数。它有什么作用?

最佳答案

除了 __printf(2,3) 之外,所有东西都非常标准(可变参数处理)。

函数的这个修饰符(类似于 staticinline 修饰符)告诉编译器它应该检查参数 2 (fmt) 针对从参数 3 开始的实际 参数,使用 printf 样式格式说明符。

换句话说,调用它:

dev_err (pDev, "%d", 1.0);

会标记警告,因为格式字符串和实际参数不匹配。

... 只是表示在格式字符串之后有可变数量的参数,类似于 printf 本身的实现方式。 C 长期以来一直具有处理变量参数列表的能力,__printf() 修饰符只是为编译器提供一些额外信息,以便它可以验证您对函数的使用。

Linux 将 __printf(a, b) 定义为 __attribute__((format(printf, a, b))) 并且 gcc 允许第二种格式指定 varargs-根据 here 检查属性(转述如下):


format (archetype, string-index, first-to-check):

The format attribute specifies that a function takes printf, scanf, strftime or strfmon style arguments which should be type-checked against a format string. For example, the declaration:

extern int my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));

causes the compiler to check the arguments in calls to my_printf for consistency with the printf style format string argument my_format.

In the example above, the format string (my_format) is the second argument of the function my_print, and the arguments to check start with the third argument, so the correct parameters for the format attribute are 2 and 3.

The format attribute allows you to identify your own functions which take format strings as arguments, so that GCC can check the calls to these functions for errors.

至于函数本身的作用,除了返回零之外没有太多:-)

如果您希望实际实现一个真正的 dev_err() 函数,几乎可以肯定它是一个占位符。

关于c - 这个通用函数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com