c - How to use macro for calling function? -
i want call function according func_name
string. code here below:
#define make_funcname func_name##hello void call_func(void* (*func)(void)) { func(); } void *print_hello(void) { printf("print_hello called\n"); } int main(void) { char func_name[30] = "print_"; call_func(make_funcname); return 0; }
but code doesn't work. want code work call_func(print_hello)
. preprocessor treated code call_func("print_hello")
. how use macro in c make exception? or not possible using c?
then problem code value of func_name
known @ run-time.
you can this:
#define make_funcname(funcname) funcname##hello void call_func(void* (*func)(void)) { func(); } void *print_hello(void) { printf("print_hello called\n"); } int main(void) { call_func(make_funcname(print_)); return 0; }
but not possible use string value within macro parameters in code snippet.
if want call functions names using string values can use table store function pointer function names this:
struct { const char *name; void (*ptr)(void); };
you can use array of structure find out function pointer @ run-time using string value. common solution using run-time strings call functions using names.
Comments
Post a Comment