gpt4 book ai didi

c - 在 ## 串联之前评估预处理器 token

转载 作者:太空狗 更新时间:2023-10-29 16:47:11 28 4
gpt4 key购买 nike

我想在将标记与其他内容连接之前对其进行评估。 “问题”是标准将行为指定为

before the replacement list is reexamined for more macro names to replace, each instance of a ## preprocessing token in the replacement list (not from an argument) is deleted and the preceding preprocessing token is concatenated with the following preprocessing token.

因此在下面的例子中,

#include <stdlib.h>

struct xy {
int x;
int y;
};

struct something {
char * s;
void *ptr;
int size;
struct xy *xys;
};
#define ARRAY_SIZE(a) ( sizeof(a) / sizeof((a)[0]) )

#define DECLARE_XY_BEGIN(prefix) \
struct xy prefix ## _xy_table[] = {

#define XY(x, y) {x, y},

#define DECLARE_XY_END(prefix) \
{0, 0} \
}; \
struct something prefix ## _something = { \
"", NULL, \
ARRAY_SIZE(prefix ## _xy_table), \
&(prefix ## _xy_table)[0], \
};

DECLARE_XY_BEGIN(linear1)
XY(0, 0)
XY(1, 1)
XY(2, 2)
XY(3, 3)
DECLARE_XY_END(linear1)


#define DECLARE_XY_BEGIN_V2() \
struct xy MYPREFIX ## _xy_table[] = {

#define DECLARE_XY_END_V2() \
{0, 0} \
}; \
struct something MYPREFIX ## _something = { \
"", NULL, \
ARRAY_SIZE(MYPREFIX ## _xy_table), \
&(MYPREFIX ## _xy_table)[0], \
};

#define MYPREFIX linear2
DECLARE_XY_BEGIN_V2()
XY(0, 0)
XY(2, 1)
XY(4, 2)
XY(6, 3)
DECLARE_XY_END_V2()
#undef MYPREFIX

最后的声明展开为

struct xy MYPREFIX_xy_table[] = {
{0, 0},
{2, 1},
{4, 2},
{6, 3},
{0, 0} }; struct something MYPREFIX_something = { "", 0, ( sizeof(MYPREFIX_xy_table) / sizeof((MYPREFIX_xy_table)[0]) ), &(MYPREFIX_xy_table)[0], };

不是

struct xy linear2_xy_table[] = {
{0, 0},
{2, 1},
{4, 2},
{6, 3},
{0, 0} }; struct something linear2_something = { "", 0, ( sizeof(linear2_xy_table) / sizeof((linear2_xy_table)[0]) ), &(linear2_xy_table)[0], };

如我所愿。有什么方法可以定义产生这个的宏吗?第一组宏确实如此,但我想避免前缀重复并且只定义一次。那么是否可以使用 #define 设置前缀并让宏使用它?

最佳答案

You can use a macro for concatenation喜欢

#define CONCAT_(A, B) A ## B
#define CONCAT(A, B) CONCAT_(A, B)

这样就可以了

#define A One
#define B Two
CONCAT(A, B) // Results in: OneTwo

关于c - 在 ## 串联之前评估预处理器 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7795514/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com