Search code examples
cgccmacrosavr

Is there a way to pass multiple values to macro function as single defined macro value in C?


I want to declare pin definition in global header as a simple line like:

#define STATUS_LED B,7

Then I want to pass this pin definition to function above:

CMBset_out(STATUS_LED);

I don't know how to approach this - MY_PIN is in proper format to be replaced during precompilation phase.

#define CMBsbi(port, pin) (PORT##port) |= (1<<pin)
#define CMBset_out(port,pin) (DDR##port) |= (1<<pin)
// define pins 
#define STATUS_LED B,7

Then, I want to pass this pin definition to function above (hw_init_states() is declared in the same header file called from main C file):

// runtime initialization
void hw_init_states(){
#ifdef STATUS_LED
    CMBset_out(STATUS_LED);
#endif
}

But I get a compilation error:

Error   1   macro "CMBset_out" requires 2 arguments, but only 1 given   GENET_HW_DEF.h  68  23  Compass IO_proto

Solution

  • An improvement upon the previous answer, which also allows you to call the macro with two explicit arguments.

    It should work with any c99 (or better) compiler:

    #define CMBset_out_X(port,pin) (DDR##port) |= (1<<pin)
    #define CMBset_out(...) CMBset_out_X(__VA_ARGS__)
    
    #define STATUS_LED B,7
    CMBset_out(STATUS_LED)
    CMBset_out(B, 7)