oscargomezf
oscargomezf

Reputation: 117

Error using macros inside functions in C

He everyone,

I'm trying to use this macro in c:

#define CONTROL_REG(num_device) CONTROL_DEV_##num_device

But it doesn't work. This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#define CONTROL_DEV_0 0x00  /* control register for device 0 */
#define CONTROL_DEV_1 0x01  /* control register for device 1 */
#define CONTROL_DEV_2 0x02  /* control register for device 2 */
#define CONTROL_DEV_3 0x03  /* control register for device 3 */

#define CONTROL_REG(num_device) CONTROL_DEV_##num_device

void func(int num_device)
{
    printf("Value: %d\n", CONTROL_REG(num_device));
}

int main(int argc, char **argv)
{
    func(0);
    func(1);
    func(2);
    func(3);
}

Any suggestion?

Best regards.

Upvotes: 2

Views: 57

Answers (2)

Since you require a run-time mapping for values, use a proper function that maps via an array:

int control_reg(int num_device) {

   static int ret[] = {
     CONTROL_DEV_0,
     CONTROL_DEV_1,
     CONTROL_DEV_2,
     CONTROL_DEV_3,
   };

   assert(num_device >= 0 && num_device <= 3);
   return ret[num_device];
}

You can't expand a macro by a run-time value.

Upvotes: 4

unwind
unwind

Reputation: 399753

Please remember that macros are completely implemented by the preprocessing step. When the actual compiler sees the code, all macros (definitions and uses) are gone.

So, this can never work.

Upvotes: 2

Related Questions