如何连接,评估和字符串化宏? [英] How to concatenate, evaluate and stringify macros?
本文介绍了如何连接,评估和字符串化宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对宏串联的替换(评估)进行字符串化.例如:
I am trying to stringify the substitution (evaluation) of a macro concatenation. For example:
#include <stdio.h>
#define FOO_ONE 12
#define FOO_TWO 34
#define BAR_ONE 56
#define BAR_TWO 78
#define MAKE_MAC(mac) // ... what to do here?
void main(int argc, char *argv[])
{
printf("FOO: " MAKE_MAC(FOO) "\n");
printf("BAR: " MAKE_MAC(BAR) "\n");
}
我正在寻找的结果是:
FOO: 1234
BAR: 5678
我尝试了几种形式,我认为最好的尝试是这样:
I tried a few forms, I think the best attempt is this:
#define STRINGIFY(mac) #mac
#define CONCAT(mac1, mac2) STRINGIFY(mac1 ## mac2)
#define MAKE_MAC(mac) CONCAT(mac, _ONE) CONCAT(mac, _TWO)
但是,这只让我走了这么远:
But, it only gets me this far:
FOO: FOO_ONEFOO_TWO
BAR: BAR_ONEBAR_TWO
那么,如何在字符串化之前添加额外的评估结果级联宏的步骤?
So, how can I add the extra step of evaluation of the resulting concatenated macro, before it gets stringified?
推荐答案
尝试一下:
#include <stdio.h>
#define FOO_ONE 12
#define FOO_TWO 34
#define BAR_ONE 56
#define BAR_TWO 78
#define STRINGIFY(arg) #arg
#define CONCAT(arg1, arg2) STRINGIFY(arg1) STRINGIFY(arg2)
#define MAC(arg) CONCAT(arg##_ONE, arg##_TWO)
int main(){
printf("FOO: " MAC(FOO) "\n");
printf("BAR: " MAC(BAR) "\n");
return 0;
}
我的输出:
FOO: 1234
BAR: 5678
这篇关于如何连接,评估和字符串化宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文