Steven
Steven

Reputation: 871

How to pass macro function as parameter

I have a macro function define and implement like this:

#define TASK(k) void task_##k(void)
TASK(T1){ // expand to void task_T1(void)
 //.....do something
}

I call task_T1() in main function can work, but when I assign task_T1 to (void)(*fptr)(void) would get wrong.

I wondering are there any possible to pass task_T1 as function pointer into another function?

Upvotes: 0

Views: 41

Answers (1)

0___________
0___________

Reputation: 67476

some options

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TASK(k) task_##k

void TASK(T1)(void){ // expand to void task_T1
printf("T1\n");
}

#define TASKNAME(k) task_##k
#define TASK1(k) void TASKNAME(k)(void)
#define TASKCALL(k) TASKNAME(k)()

TASK1(T2)
{
    printf("T2\n");
}

void (*ptr)(void) = TASK(T1);
void (*ptr1)(void) = TASKNAME(T2);


int main(void)
{
    TASK(T1)();
    ptr();
    TASKNAME(T2)();
    TASKCALL(T2);
    ptr1();
}

Upvotes: 1

Related Questions