Macro evaluation in c preprocessor

a 夏天 提交于 2019-12-10 18:49:48

问题


I'd like to do something like this:

#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO(num,...) MYMACRO##num(__VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)

And I expected it to evaluate to "two args". But instead I have

MYMACRONUM_ARGS()(1,1)

Is there a way to do what I want (using visual c++) ?

P.S. Eventually I want to implement logger that dumps all of variables. The next code

int myInt = 7;
string myStr("Hello Galaxy!");
DUMP_VARS(myInt, myStr);

will produce log record "myInt = 7; myStr = Hello Galaxy!"


回答1:


You need another macro because macro expansion does not take place near # or ##:

#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO_AUX(num,...) MYMACRO##num(__VA_ARGS__)
#define MYMACRO(num,...) MYMACRO_AUX(num, __VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)

#include <stdio.h>

int main(void)
{
    puts(GENERATE(0, 1));

    return 0;
}

If this is what you're trying to do, but complicated preprocessor tricks are not really safe, as others already said, don't do it unless you really have to.



来源:https://stackoverflow.com/questions/13970749/macro-evaluation-in-c-preprocessor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!