GNU C preprocessor: Stringify the result of a macro evaluation

北战南征 提交于 2019-12-11 12:59:05

问题


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.



来源:https://stackoverflow.com/questions/11233596/gnu-c-preprocessor-stringify-the-result-of-a-macro-evaluation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!