Wednesday, June 08, 2005

#define problem

#define is evil, filched from Stroustrup's 'The C++ programming language'. Experienced this the last week.
The problem
Library A: having a.h, library B: having b.h, and my code requiring both.
a.h has #define DEBUG 0, and b.h has const int DEBUG = 1.
If included in the order b.h, and a.h things work fine, otherwise all hell breaks loose. Fix was to do some more macro magic,
#ifdef DEBUG
#define OLD_DEBUG DEBUG
#undef DEBUG
#endif
and after the include of b.h ,restore the state of DEBUG from OLD_DEBUG. This worked thankfully.


3 comments:

Subhash Chandra said...

I am just tempted to comment here, thats why I am doing it.

Well it is not #define which is evil, but it is the programmer who is evil. A good programmer knows that he is developing a component or a library or whatever which is going to be used by others needs to protect his name space, also he should be aware that there are many programmers who doesn't protect their name space.

Life will be pretty simple in that case.

test123 said...

True.. can't disagree with that. But the lesser of two evils would be for the programmer to not clobber others code inadvertently using #defines, since they don't honour scopes, so a typedef in this case atleast would have been better. My 2c

sudeep said...

hey subhash,

long time dude !
hope u r doing cooL

:))