hlo*_*dal 11 c string-concatenation stringification c-preprocessor
我想在它与其他东西连接之前评估一个令牌."问题"是标准将行为指定为
在重新检查替换列表以更换更多宏名称之前,删除替换列表中的##预处理标记的每个实例(不是来自参数),并将前面的预处理标记与以下预处理标记连接起来.
因此在下面的例子中,
#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
Run Code Online (Sandbox Code Playgroud)
最后一个声明扩展为
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], };
Run Code Online (Sandbox Code Playgroud)
并不是
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], };
Run Code Online (Sandbox Code Playgroud)
就像我想的那样.有没有一种方法来定义产生这个的宏?第一组宏确实如此,但我想避免前缀重复,只定义一次.那么可以设置前缀#define并让宏使用它吗?
don*_*nes 13
#define CONCAT_(A, B) A ## B
#define CONCAT(A, B) CONCAT_(A, B)
Run Code Online (Sandbox Code Playgroud)
这样就行了
#define A One
#define B Two
CONCAT(A, B) // Results in: OneTwo
Run Code Online (Sandbox Code Playgroud)
您可以为此使用二级扩展,例如。
#define XY_HLP1(a) DECLARE_XY_BEGIN(a)
#define XY_HLP2(a) DECLARE_XY_END(a)
#define DECLARE_XY_BEGIN_V2() XY_HLP1(MYPREFIX)
#define DECLARE_XY_END_V2() XY_HLP2(MYPREFIX)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3128 次 |
| 最近记录: |