Reputation: 6260
I'm including header files which require certain pro-processor #define
s 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:
Will the above work i.e. restore all macro definitions (or lack of) to the state they were in beforehand?
Is there perhaps a simpler solution?
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
Reputation: 2580
Upvotes: 1
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