允许 llvm/clang 查看枚举标签的文本?

Allow llvm/clang to see the text of enum tag?

我目前在 C 代码中有以下枚举。例如,

typedef enum {
  FIRST,
  SECOND,
  LAST
}

我正在尝试对标签进行检测,并编写了一个通过 C 代码的模块传递。但是,我注意到枚举标签已经解析为整数。它只显示为数字,原始文本消失了。但我也希望枚举的名称也显示出来。

我想知道是否有技巧可以做到这一点?

感谢您的潜在帮助。

X Macros这是一个很好的任务:

#include <stdio.h>

#define COLOR_TABLE \
X(red, "red")       \
X(green, "green")   \
X(blue, "blue")

#define X(a, b) a,
enum COLOR {
  COLOR_TABLE
};
#undef X

#define X(a, b) b,
char *color_name[] = {
  COLOR_TABLE
};
#undef X

int main() {
  enum COLOR c = red;
  printf("c=%s\n", color_name[c]);
  return 0;
}

另一种方式(使用字符串化):

#include <stdio.h>

#define COLOR_TABLE \
X(red)   \
X(green) \
X(blue)

#define X(t) t,
enum COLOR {
  COLOR_TABLE
};
#undef X

#define X(t) #t,
char *color_name[] = {
  COLOR_TABLE
};
#undef X

int main() {
  enum COLOR c = red;
  printf("c=%s\n", color_name[c]);
  return 0;
}