将函数指针名称传递给C预处理器

时间:2013-10-19 22:03:33

标签: c function-pointers c-preprocessor

我的 C 代码中有函数注册表,我必须提供一个API,以便在编译时将自定义函数注册到注册表。

实施例: 代码的“客户”方面应该是:

int a_test_function_a(){
    return 13;
}
int init(void){
    add_command(a_test_function_a);
}

在我的注册表代码中,我定义了这个宏:

#define add_command(NAME)   do{                 \
    command_registry = avl_tree_add(            \
    command_registry                            \
    , #NAME                                     \
    , &##NAME                                   \
    , &command_handler);                        \
    } while(0)

这是我不明白的。 gcc -E的输出替换了预期的字符串:

do{ command_registry = avl_tree_add( command_registry , "a_test_function_a" , &a_test_function_a , &command_handler); } while(0);

但编译器抛出错误:

src/commands/commandRegisterTest.c:18:5: error: pasting formed '&a_test_function_a', an invalid
  preprocessing token
add_command(a_test_function_a);
^
src/commands/../../../src/commands/command_api.h:18:8: note: expanded from macro 'add_command'
, &##NAME                                   \
   ^
1 error generated.

我怎么能这样做,我不必自己打电话给add_command('name', &function);。我将按名称注册该函数,然后调用add_command(name)。 除了解决方案之外,为什么预处理器会替换线路但是会失败?这对我没有任何意义。

1 个答案:

答案 0 :(得分:2)

函数和函数指针通常是等价的,即你可以simply omit the & ##并且它仍然会工作,但预处理器会很高兴。

无论如何,您只需删除##运算符,它也可能正常运行。 & var很好,所以不需要连接。