質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top