使用C中的宏生成带字符串的函数名称

joh*_*han 8 c c-preprocessor

我有两个功能:

void foo0(int bar);
void foo1(int bar);
Run Code Online (Sandbox Code Playgroud)

我不能创建一个宏QUX,它将根据另一个宏扩展到这些函数名称BAZ.我尝试了以下方法:

#define BAZ 0
#define QUX(x) foo##BAZ(x)
Run Code Online (Sandbox Code Playgroud)

但是由于生成的函数是无效的,所以它不起作用fooBAZ().我怎样才能让它生成foo0()

BLU*_*IXY 8

#define CAT_I(a,b) a##b
#define CAT(a,b) CAT_I(a, b)
#define QUX(x) CAT(foo, BAZ) ## (x)
Run Code Online (Sandbox Code Playgroud)

  • 必须有理由让中间的`#define CAT(a,b)CAT_I(a,b)`.你能详细说说吗? (6认同)

Jey*_*ram 6

#include <stdio.h>

#define ONE 1
#define ZERO 0

#define GLUE_HELPER(x, y) x##y
#define GLUE(x, y) GLUE_HELPER(x, y)

int foo0(int x)
{
    printf("\n foo0...%d\n", x);
}

int foo1(int x)
{
    printf("\n foo1...%d\n",x);
}

int main()
{
   //Calling Function
   GLUE(foo,ZERO)(5);    
   GLUE(foo,ONE)(10);    
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

将按预期工作.你必须在二级宏扩展中进行字符串连接.