头文件中的“...”参数是否需要包含 stdarg.h ?

Jac*_*row 4 c arguments header-files variadic-functions

#ifndef WHATEVER_H
#define WHATEVER_H

void test(const char *format, ...); // would you have to #include <stdarg.h> for ... on argument, or is it ok if you don't use it

#endif // WHATEVER_H
Run Code Online (Sandbox Code Playgroud)

因此,如果我有一个像这样的头文件,我需要将其...作为我的void test函数的参数,我是否必须包含 stdarg.h 作为...参数,或者它不是强制性的?

Jon*_*ler 6

<stdarg.h>如果原型仅包含省略号 ( ) 符号,则不需要包含标头, ...。实现该test()函数的代码需要包含<stdarg.h>,但声明它的标头不需要。

\n

但是,您通常应该考虑创建第二个函数,void vtest(const char *format, va_list args);以匹配test()标头中的函数,然后您确实需要<stdarg.h>定义va_list类型(并且实现代码不再需要单独的#include <stdarg.h>)。通过vtest()标头中的声明,函数的实现test()变得微不足道:

\n
void test(const char *format, ...)\n{\n    va_list args;\n    va_start(args, format);\n    vtest(format, args);\n    va_end(args);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这特别简单,因为没有要中继的返回值,但返回值也不是很难。使用此方案来实现可变参数函数通常是一个好主意test(),即使您不公开函数vtest()\xe2\x80\x94 ,您很可能最终会想要它提供的额外灵活性。

\n