Question

Imagine you have many identifiers such as UARTxREG (where x is a number).

Is there a way to write a macro such as:

#define CHANNEL_ONE 1
#define UART_REG(channel)
/* Later */
UART_REG(CHANNEL_ONE) = 1;

So that this will expand to:

UART1REG

I can do this is a pass the literal numbers (1,2,3 etc..) into the macro but when I try to pass in a macro I get into the problem of the macro not expanding correctly.

I currently have:

#define STRINGIFY(x) #x
#define UART_REG(channel)            STRINGIFY(UART##channel##REG)
/* Later */
UART_REG(UART_ONE) = regVal;

However this is not expanding channel.

Was it helpful?

Solution

You don't need to stringify:

#include <stdio.h>

#define CHANNEL_ONE 1
#define UARTREG_(channel) UART##channel##REG
#define UART_REG(channel) UARTREG_(channel)

int main(void)
{
    char UART1REG = 'a';
    char UART2REG = 'b';
    char UART3REG = 'c';

    UART_REG(CHANNEL_ONE) = 'd';

    printf("%c\n", UART_REG(CHANNEL_ONE));

    return 0;
}

OTHER TIPS

You may have to wrap your concatenation to another macro:

#define STRINGIFY(x) #x
#define UART_REG2(channel)           STRINGIFY(UART##channel##REG)
#define UART_REG(channel)            UART_REG2(channel)

Note that STRINGIFY-macro makes your result "UART1REG" which may not be what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top