Alex Rivera | Logout

Preserving preprocessor definitions

Asked 2010-11-08T21:14:36.200
24

Possible Duplicate:
Can I redefine a C++ macro then define it back?

Say I have some code that uses the name BLAH for a variable. Suppose BLAH is a common preprocessor definition in many standard header files (defined as 10), so if my file is included after any of them, the code breaks because BLAH is transformed into 10; therefore, I must #undef BLAH. But also other headers may depend on BLAH, so I must restore BLAH to it's original value after my header is done. Is it possible to do something like this:

#ifdef BLAH
#define BLAH_OLD BLAH
#undef BLAH
#endif

... code ...

// restore BLAH to 10
#ifdef BLAH_OLD
#define BLAH BLAH_OLD
#end

? This doesn't work of course, because BLAH is not expanded to 10. I have tried doing something like

#define EXPAND_AGAIN(x) x
#define EXPAND(x) EXPAND_AGAIN(x)
#define BLAH_OLD EXPAND(BLAH)

but that doesn't work either, since EXPAND is taken literally and not expanded. I am using MSVC 2008/2010, but it would be lovely if the solution would work on most other compilers too.

Edit
Report

1 Answer

-4

One trick that works for me is to use an enum in the class.

class foo
{
public:
  enum { blah = 10 } myenum;
}

Then you can just use

foo:blah

when you need '10'.

Since it's part of the class then other uses of 'blah' won't conflict and you save all that def'ing and undef'ing.

answered 2010-11-08T21:29:57.317

Your Answer