views:

33

answers:

2

I am working on embedded code and attempting to convert a lot of memory-mapped register assignments to get()/set() function calls. I was wondering if it would be possible to maintain the address assignments sprinkled throughout the code, but change the #defines so they take the assignment in as a function argument.

Old Way:

#define MOTOR_REG (*(volatile unsigned char *)(0xFEE002));  //a memory-mapped register
MOTOR_REG = value;        //sets value into the memory-mapped register

Desired New Way:

#define MOTOR_REG( set_motor_reg(value); )

void set_motor_reg(unsigned char)
{
   //logic to set the motor register
}

MOTOR_REG = value;       //value should be passed in to MOTOR_REG macro

So, is this scenario possible with C macros? Thanks for your thoughts!

+1  A: 

You can't do exactly what you want with macros. (You could do this in C++ with operator overloading, but that's probably not an option).

Why are you converting everything to functions if you want to continue using things as if they were variables?

Oli Charlesworth
+2  A: 

C macros won't allow you to do exactly this, as they are just an advanced search & replace done by the preprocessor. You might however pass the value as a macro parameter:

#define MOTOR_REG(value) set_motor_reg(value)

void set_motor_reg(unsigned char) { //logic to set the motor register }

MOTOR_REG(value); //value is passed in to MOTOR_REG macro

In the above case, using MOTOR_REG is of course unnecessary as you might call set_motor_reg directly. If you are allowed to use C++, you can achieve the wanted behavior that with operator overloading.

dark_charlie
semicolon in macro?
Nyan
@Nyan: Thanks, fixed.
dark_charlie