GNU C预处理器:字符串化宏评估的结果 [英] GNU C preprocessor: Stringify the result of a macro evaluation

查看:145
本文介绍了GNU C预处理器:字符串化宏评估的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的字符串宏,如果可能的话,我想将其转换为一个长度值字符串,所有都在宏内,因此所有内容都以.rodata结尾.

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)

我想将PAYLOAD_LEN用作字符串,例如在另一个字符串的一部分中.

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"`

我怀疑这是不可能的,我应该只将PAYLOAD_LEN定义为文字,例如#define PAYLOAD_LEN 3,然后字符串化.

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.

我可以但不想忘记.rodata并在运行时生成它,例如

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是由编译器而不是预处理器处理的,因此您不能采用这种方法.其他两个选项将起作用,哪个更适合取决于您的情况.

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.

这篇关于GNU C预处理器:字符串化宏评估的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆