首页 > 解决方案 > 如何使用可变参数宏?

问题描述

我正在尝试使用可变参数宏。我希望从 MY_TOP_PRINTF 宏中调用 PRINTF 宏。

1.要么我得到编译错误。

2.如果我删除编译错误,它只打印第一个参数。

我的预期结果是Inside TOP_PRINT dog here 4

#include <iostream>
#include <cstdio>

using namespace std;


#define PRINTF(str, ...)  {                             \
    fprintf(stderr, (str), ##__VA_ARGS__);              \
}


#define MY_TOP_PRINTF(EXPRESSION, ...) {                \
    PRINTF("Inside TOP_PRINT ", EXPRESSION, __VA_ARGS__);\
}


int main()
{
    int x = 4;
    char str[255] = "dog here";

    MY_TOP_PRINTF(str,x);
    return 0;
}

错误:

hello_temp.cpp: In function ‘int main()’:
hello_temp.cpp:8:41: warning: too many arguments for format [-Wformat-extra-args]
     fprintf(stderr, (str), ##__VA_ARGS__);  \
                                         ^
hello_temp.cpp:13:5: note: in expansion of macro ‘PRINTF’
     PRINTF("Inside TOP_PRINT", EXPRESSION, __VA_ARGS__);\
     ^
hello_temp.cpp:23:2: note: in expansion of macro ‘MY_TOP_PRINTF’
  MY_TOP_PRINTF(str,x);

标签: c++macros

解决方案


推荐阅读