GNU C preprocessor: Stringify the result of a macr

2019-08-07 10:29发布

问题:

I have a common string macro that I want to convert to a length-value string, all within macros, if possible, so everything ends up in .rodata.

#define PAYLOAD "xyz"
#define PAYLOAD_LEN (sizeof(PAYLOAD)-1)

I would like to use PAYLOAD_LEN, as a string, in part of another string, e.g.

const char lv_macro[]  = "<preamble>" PAYLOAD_LEN ":" PAYLOAD;
const char lv_wanted[] = "<preamble>3:xyz"`

I suspect that this is not possible, and that I should just define PAYLOAD_LEN as a literal, e.g. #define PAYLOAD_LEN 3 and then stringify.

I could, but do not want to, forget about .rodata and generate it at run-time, e.g.

char lv[64];
snprintf(lv, sizeof lv, "<preamble>%zu:" PAYLOAD, PAYLOAD_LEN);

Please note that this is not the question that has been asked and answered already here, for example, and in many other questions.

回答1:

sizeof is handled by the compiler, not the preprocessor, so you can't take that approach. The other two options will work, and which one is better suited depends on your circumstances.