Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define a tuple in C

I want to be able to define a tuple which represents the arguments needed by other macros.

I think the best way to show what I want is to show an example:

#include <avr/io.h>

#define LED_PORT PORTB
#define LED_DDR  DDRB
#define LED_PIN  PB7
#define LED      LED_PORT, LED_DDR, LED_PIN

#define OUTPUT(port, ddr, pin) ddr |= 1 << pin

void main(void) {
    OUTPUT(LED);
}

I want OUTPUT(LED) to be then expanded into:

LED_DDR |= 1 << LED_PIN

The problem that I get is to do with the order of expansion, and results in the following error:

macro "OUTPUT" requires 3 arguments, but only 1 given

This is for use with an AVR project with custom built hardware where I have defined LED and other components with a respective LED_PORT LED_DDR and LED_PIN.

I then want to define more macros that can take this LED and use the appropriate arguments to map to the most succinct way possible.

Is this possible with the standard C-preprocessor?

like image 732
flungo Avatar asked Apr 27 '15 13:04

flungo


1 Answers

You can add a level of indirection to the macro to achieve this:

#define OUTPUT_I(port, ddr, pin) ddr |= 1 << pin
#define OUTPUT(spec) OUTPUT_I(spec)

During rescanning, spec is expanded before OUTPUT_I, so the OUTPUT_I macro sees three parameters.

like image 74
Wintermute Avatar answered Oct 15 '22 18:10

Wintermute