c - 如何让 C 在给定数字宏值的情况下找到宏标识符?

标签 c c-preprocessor

假设我有一些 C 代码,例如:

#define FOO 2
#define BAR 3
#define BAZ 500

void get_value(int val) {
  printf("The value is %s\n", some_function_or_macro_or_something(val));
}

int main(int argc, char** argv) {
  get_value(BAZ);
  get_value(FOO);
  return 0;
}

我想把它打印出来 “值(value)是BAZ” 和 “值(value)是 FOO”。但是有成千上万的#defines,所以我想以编程方式进行。

最佳答案

C 绝对能够使用 # 字符串化运算符来执行此操作,但您需要直接调用带有标识符的宏:

#include <stdio.h>

#define FOO 2
#define BAR 3
#define BAZ 500

#define get_value(val)     \
  printf("The value is %s\n", #val);

int main(void)
{
  get_value(BAZ);
  get_value(FOO);

  return 0;
}

在您的示例中,在传递例如值之后BAZget_value 函数, token BAZ 不再被识别,因为参数是按值传递的。换句话说,宏标识符不见了(当然你仍然可以将其替换字符串化,见下面的评论)。

我还能做些什么?

这里有一些小 hack 来遵守这个“顶级”规则。假设您有少量具有唯一值的类对象宏(常量),那么您可以执行以下操作:

#include <stdio.h>

#define FOO 2
#define BAR 3
#define BAZ 500

#define STRINGIFY(val) #val

void get_value(int val) {
  switch (val) {
    case FOO :
      printf("The value is %s\n", STRINGIFY(FOO)); break;
    case BAR :
      printf("The value is %s\n", STRINGIFY(BAR)); break;
    case BAZ :
      printf("The value is %s\n", STRINGIFY(BAZ)); break;
  }
}

int main(int argc, char* argv) {
  get_value(BAZ);
  get_value(FOO);
  return 0;
}

结果:

The value is BAZ
The value is FOO

关于c - 如何让 C 在给定数字宏值的情况下找到宏标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28098040/

相关文章:

c - 格式字符串的预处理器和替换

单位与多位的 c 位操作

c - 将数据从串行端口传输到文本文件

c - 简单的 Linux IPC 问题

用于重复使用 std::xyz 语句的 C++ 宏

c++ - 如何检测我是否正在为 C++ 中的 64 位架构进行编译

ios - Apple Watch 的预处理器宏?

c++ - 如何只用一个#define 定义两个或多个值?

c - 获取 C 结构成员列表

c - gcc 错误 - ld : fatal: file shmonitor. o 错误的 ELF 类:ELFCLASS64