宏值的字符串化 [英] Stringification of a macro value
问题描述
我面临一个问题 - 我需要使用宏值同时作为字符串和整数
I faced a problem - I need to use a macro value both as string and as integer.
#define RECORDS_PER_PAGE 10
/*... */
#define REQUEST_RECORDS \
"SELECT Fields FROM Table WHERE Conditions" \
" OFFSET %d * " #RECORDS_PER_PAGE \
" LIMIT " #RECORDS_PER_PAGE ";"
char result_buffer[RECORDS_PER_PAGE][MAX_RECORD_LEN];
/* ...and some more uses of RECORDS_PER_PAGE, elsewhere... */
这失败,一个关于流浪#消息,即使它的工作,我想我会得到的宏名字符串化,而不是值。当然,我可以养活值到最后的方法(LIMIT%D,页* RECORDS_PER_PAGE
),但它既不pretty,也没有效率。
这几次都是这样,当我希望preprocessor没有以特殊的方式对待字符串,将处理它们的内容就像正常的code。
现在,我与 cludged它的#define RECORDS_PER_PAGE_TXT10
,但可以理解的,我不开心了。
This fails with a message about "stray #", and even if it worked, I guess I'd get the macro names stringified, not the values. Of course I can feed the values to the final method ( "LIMIT %d ", page*RECORDS_PER_PAGE
) but it's neither pretty nor efficient.
It's times like this when I wish the preprocessor didn't treat strings in a special way and would process their content just like normal code.
For now, I cludged it with #define RECORDS_PER_PAGE_TXT "10"
but understandably, I'm not happy about it.
如何得到它的权利?
推荐答案
下面定义的 XSTR
宏将做宏扩展后的字符串化。
The xstr
macro defined below will stringify after doing macro-expansion.
#define xstr(a) str(a)
#define str(a) #a
#define RECORDS_PER_PAGE 10
#define REQUEST_RECORDS \
"SELECT Fields FROM Table WHERE Conditions" \
" OFFSET %d * " xstr(RECORDS_PER_PAGE) \
" LIMIT " xstr(RECORDS_PER_PAGE) ";"
这篇关于宏值的字符串化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!