GNU C preprocessor: Stringify the result of a macro evaluation
Asked Answered
C

1

1

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.

Chaudfroid answered 27/6, 2012 at 19:29 Comment(1)
possible duplicate of Embed result of sizeof() offsetof() macros into a const char array?So
E
3

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.

Eel answered 27/6, 2012 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.