字符串作为 C 中带参数的宏

String as macro with arguments in C

考虑以下字符串:

Page 1 of 100

其中1100不是固定值。

我如何定义 C 宏以便通过将两个值作为参数传递来呈现该字符串?

为了清楚起见,格式必须如下所示:

#define PAGE_IDX_MACRO(x,y)

您可以通过双哈希标签连接字符串:

## provides a way to [concatenate actual arguments][1] during macro expansion.

[1]: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc09numnum.htm

来自这个问题:

What do two adjacent pound signs mean in a C macro?

# 运算符将预处理器标记转换为字符串文字。

字符串文字在 C 中通过简单地在它们之间添加 space 来连接,即 "hello" "world" 等同于 "helloworld".

所以宏应该是:

#define PAGE_IDX_MACRO(x, n) ("Page " #x " of " #n)

假设这样调用:

PAGE_IDX_MACRO(1, 100);

其中 1 和 100 是编译时常量。