如何使宏返回字符而不是字符串?

时间:2015-01-16 09:55:43

标签: c generics macros

我有以下宏(跟进:When writing a macro in C, how do I find the type and printf specifier for an argument?):

#define mu_format_specifier(expression) _Generic((expression), unsigned long: "%lu", int: "%i")

#define mu_assert_equal(actual, expected) do {                                                      \
  if (actual != expected) {                                                                         \
    char *message = malloc(MAX_ERROR_MESSAGE_LENGTH);                                               \
    if (message == NULL) { printf("malloc failed"); exit(1); }                                      \
    snprintf(message, MAX_ERROR_MESSAGE_LENGTH,                                                     \
      "required: %s != %s, reality: %s == " mu_format_specifier(actual),                            \
      #actual, #expected, #actual, actual);                                                         \
    return message;                                                                                 \
  }                                                                                                 \
} while (0)

问题是mu_format_specifier 似乎要求解析为char *,而不是简单地将"%lu"替换为"required: %s != %s, reality: %s == " mu_format_specifier(actual),我希望得到"required: %s != %s, reality: %s == " "%lu" _Generic C将理解为一个文字字符串。

我可以看到两个可怕的工作:

  1. 为每种类型制作mu_assert_equal版本的版本,并使用const调用正确的版本。

  2. snprintf格式化字符串,但如果格式化字符串必须为_Generic,我可能会遇到问题。

  3. 有更好的选择吗?

    (问题是"%lu"实际上是在评估表达式,而不是简单地替换源字符 - 即"required: %s != %s, reality: %s == "成为它自己的文字字符串,而不仅仅是生成源字符。与{{1}}统一。)

1 个答案:

答案 0 :(得分:0)

我做到了:

#define mu_assert_equal(actual, expected) do {                                            \
  if (actual != expected) {                                                               \
    char *message = malloc(MAX_ERROR_MESSAGE_LENGTH);                                     \
    if (message == NULL) { printf("malloc failed"); exit(1); }                            \
    snprintf(message, MAX_ERROR_MESSAGE_LENGTH, _Generic(                                 \
        (actual),                                                                         \
        unsigned long: "required: %s != %s, reality: %s == %lu",                          \
        int:           "required: %s != %s, reality: %s == %i"                            \
      ),                                                                                  \
      #actual, #expected, #actual, actual);                                               \
    return message;                                                                       \
  }                                                                                       \
} while (0)

解决方案是使整个格式化字符串成为_Generic的输出表达式

从测试代码:

mu_assert_equal(bytes_parsed, 1);

我得到输出:

required: bytes_parsed != 1, reality: bytes_parsed == 0