ss2_d
ss2_d

Reputation: 1

Using macros to generalise code for function calls

I'm writing C code which requires me to use multiple function calls of the same definition which differ only by single characters. Is there a way I can make a macro function which takes say a number and can insert these calls into my code for me where I call the macro given I know the numbers at compile time:

i.e.

#define call_pin_macro(X)
    enable_pin#X();
    do_thing_pin#X();
    do_other_thing_pin#X();
            .
            .
void pin_function(void){
    call_pin_macro(1);
    call_pin_macro(2);
    call_pin_macro(3);
}

Instead of:

void pin_function(void){
     enable_pin1();
     do_thing_pin1();
     do_other_thing_pin1();
     enable_pin2();
     do_thing_pin2();
     do_other_thing_pin2();
     enable_pin3();
     do_thing_pin3();
     do_other_thing_pin3();

}

As a note I have looked at stringification (Hence the included #X's) in gcc however I cannot get the above code to compile which I get an error "error: '#' is not followed by a macro parameter". And it thus it seems this isn't exactly the functionality I am after. Thanks in advance.

Upvotes: 0

Views: 81

Answers (1)

samgak
samgak

Reputation: 24417

In gcc you can do it like this:

#define call_pin_macro(X)   \
    enable_pin##X();           \
    do_thing_pin##X();         \
    do_other_thing_pin##X();

The double hash is the macro concatenation operator. You don't want to use stringify because that will put quotes around it.

The backslashes allow you to continue the macro over several lines.

Upvotes: 2

Related Questions