Variadic Macro调用fprintf:如何向__VA_ARGS__添加参数?

Par*_*duz 3 c macros printf variadic-macros

我有两个宏:

 #define LogFunction(str)       fprintf(stdout, "%s: %s\n",__FUNCTION__,(str))
 #define LogPrintf(f_, ...)     fprintf(stdout, (f_), ##__VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

所以我可以这样使用它们:

void MyFunction()
{
    int N=4;
    LogFunction("START");      // Outputs "MyFunction: START"
    LogPrintf("N=%d\n", N);    // Outputs "N=4"
}
Run Code Online (Sandbox Code Playgroud)

我想改变的是

  1. 在LogPrintf的开头添加FUNCTION,就像在LogFunction中一样
  2. 在LogPrintf的末尾添加"\n",而不必记住把它放在我自己身上

所以最后我的输出只能有一个宏.

我试图了解附加到__VA_ARGS__是否有用,但我承认我不明白它是否与我的情况有关:(

谢谢.

Jea*_*bre 5

为什么不分3步呢?

#define LogPrintf(f_, ...)   do { fprintf(stdout, "%s: ",__FUNCTION__); \
                                  fprintf(stdout, (f_), ##__VA_ARGS__); \
                                  fprintf(stdout,"\n"); } while(0)
Run Code Online (Sandbox Code Playgroud)

这可以打印3张,但至少它很简单,可以做你想要的.这个do while(0)技巧确保这是一个唯一的块(当使用if没有大括号时)并且需要分号.