C Macro Token Concatenation involving a variable - is it possible?

gatesphere picture gatesphere · Sep 3, 2010 · Viewed 13.4k times · Source

I'm trying to define a macro to generate a token name, containing a variable.

Basically, what I'm trying is this:

#define GLUER(x,y,z) x##y##z
#define PxDIR(x) GLUER(P,x,DIR)

int main() {
  int port;
  port = 2;
  PxDIR(port) |= 0x01;
}

I'm hoping to generate the token P2DIR in the above statement, but according to my compiler output, it's generating the token PportDIR, which is NOT what I wanted. Any help here? Or is what I'm attempting to do impossible?

Answer

Hitesh picture Hitesh · Sep 3, 2010

I don't think what you're trying to do is possible. C macros are really preprocessor macros that are expanded before compilation. The variable port, doesn't get set until runtime.