0

How to populate an array of function pointers from an existing task-list Macro?

The Task List looks like this:

#define execute_list \
printhello();   \
printbye();

printhello and printbye are existing functions.

We need to populate the array of function pointers with the address of these functions.

    void (*my_fptr_array[])(void) =
   {
        &printhello,
        &printbye,
   };

This should happen automatically through a Macro. Something like:

void (*my_fptr_array[])(void) =
       {
            EXTRACT_FUNCTION(0,execute_list),
            EXTRACT_FUNCTION(1,execute_list)
       };

is this possible in C?

James Z
  • 12,209
  • 10
  • 24
  • 44
pawan kumar
  • 33
  • 1
  • 6
  • I think, you want to use X macros ? (https://stackoverflow.com/questions/6635851/real-world-use-of-x-macros). It is very useful to generate some code from a list. – Umaiki Oct 11 '19 at 07:36
  • Umaiki: Thank you, I am checking out X Macros now.. This is new to me.. – pawan kumar Oct 11 '19 at 07:43
  • 1
    You are out of luck because the C preprocessor can't dissect strings. It also doesn't know about syntactical elements of the C language when presented in string form. The only thing it cares for are `,` commas which can be (ab)used in compositions of macros. Maybe there is a way to strip the original definitions from the `();` part and replace it with `,` so that you are left with a preprocessable list of symbols. From there on its easy. – Vroomfondel Oct 11 '19 at 08:57
  • 1
    You are right, I miss understood. I thought the list could be changed from `XX();` to `XX`. If you cannot change the list, X macros are useless. – Umaiki Oct 11 '19 at 09:08

1 Answers1

0

You don't need a macro for that. If you have the array, you can easily execute these functions by traversing the array.

In other words, your requirement is the wrong way round. Instead of trying to extract stuff from the execution list, try building the execution list from the simpler array of function pointers.

(You could use an X macro for this, but I don't see the benefit except maybe saving a little bit of loop overhead.)

M Oehm
  • 28,726
  • 3
  • 31
  • 42
  • M Oehm : Yes, I completely agree with you. Building the array first should be the approach... but unfortunately, This is a feature addition on an existing legacy code.. Also, what i have shown here is an overly simplified version of the requirement.. – pawan kumar Oct 11 '19 at 07:40
  • 1
    In that case, a macro can't help you: You would have to strip the parentheses and turn the semicolons into a comma, and a macro can only add stuff, not take it away. Your best bet is probably to parse the existing macro with an external program and have it write out the desired list. – M Oehm Oct 11 '19 at 07:45