我应该如何在C++的类方法中正确使用__attribute __((format(printf,x,y)))?

Nat*_*man 22 c++ printf gcc string-formatting

我正在尝试为调试打印定义一个类方法,其行为类似于printf:

inline void debug(const char* fmt, ...) __attribute__ ((format (printf, 1, 2)))
Run Code Online (Sandbox Code Playgroud)

这抱怨:

error: format string argument not a string type
Run Code Online (Sandbox Code Playgroud)

我记得类方法声明有一个隐式this参数,所以我将参数的位置更改为2,3:

inline void debug(const char* fmt, ...) __attribute__ ((format (printf, 2, 3)))
Run Code Online (Sandbox Code Playgroud)

现在它编译,但看起来像参数被移位,就好像this参数被视为参数列表的一部分.

如何判断this不属于我要打印的字符串的函数?

Chr*_*odd 22

你做到了. this是参数1,所以通过说format(printf, 2, 3)你告诉编译器你不打印this,你打印参数2(fmt)以及其他参数.

  • 你是对的[这里](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes):**因为非静态C++方法有一个隐含的这个参数,当给出string-index和first-to-check的值时,这些方法的参数应该从两个而不是一个计算.** (3认同)

sag*_*age 6

将静态成员与非成员同等对待。讨论给了我答案,但其他人值得注意:

  • 非成员函数适用于 1,2
  • 静态成员函数适用于 1,2
  • 非静态成员函数将“this”视为#1,因此需要 2,3

我发现这一点是因为我们有一些进程使用这样的日志助手,并且四分之一的进程需要__attribute__ (( format( printf, 2, 3 ) ))与其他三个进程配合使用__attribute__ (( format(printf, 1, 2) ))- 事实证明它是非静态的......


Gab*_*les 5

@克里斯·多德是正确的。这是支持它的最新 gcc 文档(感谢Foxit reader让我在 Linux 上标记 PDF)。特别注意下图中绿色标记的部分。

由于非静态 C++ 方法具有隐式 this 参数,因此在为和提供值时,此类方法的参数应从2开始计数,而不是从 1 开始。string-indexfirst-to-check

来源: https: //gcc.gnu.org/onlinedocs/gcc-8.2.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes(请参阅标题为“格式(原型、字符串索引、第一个-去检查)”)。

图像(尤其是绿色突出显示):

在此输入图像描述