Peter Shaw
Peter Shaw

Reputation: 1907

Pass a function-pointer name to C Preprocessor

I have a registry for functions in my C code, and I have to provide an API to register custom functions at compile time to the registry.

Example: The "customer" side of code should like:

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

In my registry code I defined this macro:

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

Here is what I do not understand. The output of gcc -E replace the string like expected:

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

But the compiler throw a error:

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.

How can I do this, that I do not have to call add_command('name', &function); by my own. I will register the function by it's name and just call the add_command(name) thing. Besides a solution, why is the preprocessor replace the line but fails? This doesn't make any sense for me.

Upvotes: 2

Views: 2013

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318508

Functions and function pointers are usually equivalent, i.e. you can simply omit the & ## and it'll work anyway but the preprocessor will be happy.

Anyway, you can simply remove the ## operator and it'll probably work, too. & var is fine so concatenation is not necessary.

Upvotes: 2

Related Questions