C 编程 : Preprocessor, 宏作为标记

标签 c macros token c-preprocessor stringification

我正在尝试做一些概念上与此类似的事情,但似乎无法让它工作(最后显示错误)有什么想法吗?

#include <stdio.h>

int main( int argc , char const *argv[] )
{
  int abc_def_ghi = 42;
  #define SUFFIX ghi
  #define VAR(prefix) prefix##_def_##SUFFIX
  printf( "%d\n" , VAR(abc) );
  return 0;
}

// untitled:8: error: ‘abc_def_SUFFIX’ undeclared (first use in this function)

最佳答案

您只需要额外的间接访问:

#include <stdio.h>

int main( int argc , char const *argv[] )
{
  int abc_def_ghi = 42;
  #define SUFFIX ghi
  #define VAR3(prefix, suffix) prefix##_def_##suffix
  #define VAR2(prefix, suffix) VAR3(prefix, suffix)
  #define VAR(prefix) VAR2(prefix, SUFFIX)
  printf( "%d\n" , VAR(abc) );
  return 0;
}

虽然看起来多余,但其实不然。

关于C 编程 : Preprocessor, 宏作为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767683/

相关文章:

将嵌套的 for 循环转换为 C 中的递归

c++ - C++ 宏可以计算 switch 语句中的案例吗?

c - 如何解决 GCC 警告 "the address of XXX will never be NULL"?

c - 识别通过 eclipse 运行的配置

java - 基于这个或那个的正则表达式

java - 使用否定对字符串进行标记

c - 在结构体中存储标记

c - 使用 goto 控制语句进行循环,但它会跳过一个命令

c - 获取正在运行的 firefox 进程的 PID

c - C语言中如何将两个8位数据排列成一个16位数据?