JBentley
JBentley

Reputation: 6260

Define a macro then undefine it if it was previously undefined

I'm including header files which require certain pro-processor #defines to be present, however I do not want this to pollute the rest of my code e.g.:

// FOO may or may not already be defined here
#define FOO
#include "Bar.h"
#undef FOO
// FOO should be defined or not, as per the starting state

I'm thinking along the lines of:

#ifdef FOO
#define FOO_DEFINED
#endif

#define FOO
#include "Bar.h"

#ifndef FOO_DEFINED
#undef FOO
#else
#undef FOO_DEFINED
#endif

Questions:

  1. Will the above work i.e. restore all macro definitions (or lack of) to the state they were in beforehand?

  2. Is there perhaps a simpler solution?

  3. Does it matter if FOO was already defined when I #define it? Should I add another #ifndef to protect against this?

Upvotes: 0

Views: 1073

Answers (2)

armel
armel

Reputation: 2580

  1. yes it should work.
  2. I have #pragma push_macro/pop_macro("macro_name") in mind, but it might work only in gcc and MS VC++
  3. yes, it matters, you'll get a warning if it is defined again with a different value. As you state, you can shield it with #ifndef.

Upvotes: 1

Jollymorphic
Jollymorphic

Reputation: 3530

It appears that in your example, Bar.h cares only whether FOO is defined or not, and not the actual expression bound to it. Furthermore, if someone else (I presume your code example is, itself, in a header file) defines FOO and cares about the expression bound to it, you don't want to make the mistake of redefining FOO with an empty expression. If so, you might want to simplify:

#ifndef FOO
#define FOO
#define UNDEF_FOO
#endif

#include "Bar.h"

#ifdef UNDEF_FOO
#undef FOO
#endif

Upvotes: 1

Related Questions