在另一个宏中使用字符串宏

时间:2018-10-08 11:08:30

标签: c string macros

如何在C的字符串宏中使用另一个宏?

我有这个:

#define MAX_OPERATION_COUNT 10
#define MSG_TOO_MANY_OPERATIONS "Too many operations! Only the first 10 were applied."

但是我希望第二个宏改为使用第一个宏的值。例如,在Java中,我会有类似的东西:

public static final int MAX_OPERATION_COUNT = 10;
public static final String MSG_TOO_MANY_OPERATIONS = "Too many operations! Only the first " + MAX_OPERATION_COUNT + " were applied.";

有没有办法在C语言中做类似的事情?

编辑: 事实证明,该解决方案与this question的解决方案非常相似,但我认为问题本身就大不相同,应单独处理。

4 个答案:

答案 0 :(得分:8)

通常,使用printf样式的格式(EntitiesViewModel?)更容易。但是,如果您真的想进行字符串替换,则必须执行两次:

"Too many operations! Only the first %u were applied"

答案 1 :(得分:1)

您可以“参数化”第二个宏:

#define STRINGYFY(x) # x
#define PASTE_AS_STRING(s) STRINGYFY(s)

#define MAX_OPERATION_COUNT 10
#define MANY_OPERATION_COUNT 2

#define MSG_TOO_MANY_OPERATIONS_TEMPLATE(n) \
  "Too many operations! Only the first" PASTE_AS_STRING(n) " were applied."

#define MSG_TOO_MANY_OPERATIONS \
  MSG_TOO_MANY_OPERATIONS_TEMPLATE(MAX_OPERATION_COUNT)
#define MSG_MUCH_TOO_MANY_OPERATIONS \
  MSG_TOO_MANY_OPERATIONS_TEMPLATE(MANY_OPERATION_COUNT)

(刚刚看到Matt's answer,虽然差不多,但还是更长一些。不过,我仍将其保留在这里,因为我觉得这种方法使用的结构略有不同。)


您还可以定义变量并仅使用宏来初始化它们。

要定义数组,请执行

const char MSG_TOO_MANY_OPERATIONS[] = 
  MSG_TOO_MANY_OPERATIONS_TEMPLATE(MAX_OPERATION_COUNT)
const char MSG_MUCH_TOO_MANY_OPERATIONS[] =
  MSG_TOO_MANY_OPERATIONS_TEMPLATE(MANY_OPERATION_COUNT)

或定义指针做

const char * MSG_TOO_MANY_OPERATIONS = 
  MSG_TOO_MANY_OPERATIONS_TEMPLATE(MAX_OPERATION_COUNT)
const char * MSG_MUCH_TOO_MANY_OPERATIONS =
  MSG_TOO_MANY_OPERATIONS_TEMPLATE(MANY_OPERATION_COUNT)

答案 2 :(得分:0)

您可以这样做:

#define FOO "1"
#define BAR "How many foos? " FOO " foo.\n"

BAR现在扩展为

"How many foos? " "1" " foo.\n" 

这是有效的字符串文字。

答案 3 :(得分:0)

您需要将数字10设为字符串。 然后,为了“连接”字符串,您只需关闭双引号,插入代表数字的宏,然后再简单地再次打开双引号即可(不需要像Java / C ++中的任何加号运算符来获取字符串) ,以编写其余消息,例如:

#define MAX_OPERATION_COUNT "10"
#define MSG_TOO_MANY_OPERATIONS "Too many operations! Only the first " MAX_OPERATION_COUNT " were applied."