I'm currently working on some peripheral drivers for a family of microprocessors. I need to write code for devices that are very similar that in some cases only vary in the number of peripherals.
I would like to write a driver for the UART peripheral but in some devices of the family there's only one available and for others there are two. The driver for UART2 y the same as for UART1 but instead of writing to UART1FOO
register I need to write to UART2FOO
register. Knowing this I would like to write a piece of code where a macro is able to repeat a big chunk of code but replacing the number of the register reference.
The ideal solution would be something like:
// File: uartdriver.h
#if __device1__
#define PRESENT_UARTS 1
#else
#define PRESENT_UARTS 2
#endif
#for CURRENT_ITEM in MAGIC_MACRO_THAT_RETURNS_LIST(PRESENT_UARTS)
void uart#CURRENT_ITEM#_init();
#endfor
I know that this pseudo code does not exist but I have also seen people do magic with macros. I must use C code and not C++ and I'm aware that the use of macros may not be the most friendly way to write this but I don't like to repeat code with such small variations.
What would be the best solutions that mimic the pseudocode above? Any other hint or advice? Is there any other alternative to macros in this situation?
Thank you very much for your time.