Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - Evaluate preprocessor token before ## concatenation

I would like to evaluate a token before it is concatenated with something else. The "problem" is that the standard specifies the behaviour as

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.

hence in the following example,

#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

The last declaration is expanded into

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], };

and not

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], };

like I want to. Is there some way of defining macros that produces this? The first set of macros does, but I would like to avoid the prefix duplication and only have this defined once. So is it possible to set the prefix with #define and let the macros use that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a macro for concatenation like

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

this works then

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...