如何连接,评估和字符串化宏?

时间:2018-05-29 22:00:34

标签: c macros c-preprocessor evaluation

我正在尝试对宏连接的替换(评估)进行字符串化。例如:

#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

我尝试了几种形式,我认为最好的尝试就是:

#define STRINGIFY(mac) #mac
#define CONCAT(mac1, mac2) STRINGIFY(mac1 ## mac2)
#define MAKE_MAC(mac) CONCAT(mac, _ONE) CONCAT(mac, _TWO)

但是,它只能让我这么远:

FOO: FOO_ONEFOO_TWO
BAR: BAR_ONEBAR_TWO

那么,在得到字符串化之前,如何添加评估结果连接宏的额外步骤?

2 个答案:

答案 0 :(得分:3)

试试这个:

#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

答案 1 :(得分:2)

您需要通过引入一个间接层来推迟字符串化:

#define STRINGIFY_X(x) #x
#define STRINGIFY(x) STRINGIFY_X(x)
#define MAKE_MAC(mac) STRINGIFY(mac ## _ONE) STRINGIFY(mac ## _TWO)

live example on wandbox.org