如何使用宏在c中使用标记粘贴连接两个标记来进行字符串化?

问题描述 投票:0回答:1

想要连接两个标记并仅使用宏以及标记粘贴和字符串化运算符将结果转换为字符串。

#include <stdio.h>

#define concat_(s1, s2) s1##s2
#define concat(s1, s2) concat_(s1, s2)

#define firstname stack
#define lastname overflow

int main()
{
    printf("%s\n", concat(firstname, lastname));
    return 0;
}

但是上面抛出了如下未声明的错误

error: ‘stackoverflow’ undeclared (first use in this function)

尝试让

#
来字符串化
s1##s2

#define concat_(s1, s2) #s1##s2 \\ error: pasting ""stack"" and "overflow" does not give a valid preprocessing token
c string c-preprocessor token-pasting-operator
1个回答
0
投票

如果要先连接再字符串化,需要先连接,再字符串化:

#include <stdio.h>

#define concat_(s1, s2) s1##s2
#define concat(s1, s2) concat_(s1, s2)
#define string_(s) #s
#define string(s) string_(s)

#define firstname stack
#define lastname overflow

int main()
{
    printf("%s\n", string(concat(firstname, lastname)));
    return 0;
}

仅向

#
宏添加
concat_
的问题是它会尝试在连接之前进行字符串化。

© www.soinside.com 2019 - 2024. All rights reserved.