Why should macro's be avoided in C++
Macros cross scope boundaries, as your example description loudly reports.
Does it just come down to compilation order (random)?
I never have random compilation order, but I use makefiles where the dependencies control the order. Note, your builds should also be repeatable.
Is there a way to do this? [redefine the macro to change only where desired]
Possibly ... can you reliably "#undef PRODUCT" just before the defining the second "#define PRODUCT ..." AND not have the second definition seen by code in which you want the first definition.
Consider:
create two zones in your code ...
#define PRODUCT "MY PRODUCT B"
// zone a
#undef PRODUCT
#define PRODUCT "NEW PRODUCT D"
// zone b
#undef PRODUCT
Put code corresponding to and dependent on the definition in to the appropriate zone.
One solution:
I had macro surprises with a 3rd party code containing macros which messed with my symbol names. Its as if they had defined macros with commonly used meaning like: open, close, read, write, etc. My method "Foo_t::open()" etc. would be stomped on.
I solved this issue (perhaps clumsily) by
- including the 3rd party header in one cpp ONLY, such that the 'macros' I did use were only invoked by the code I wrote to use it, not in any other compilation unit. (i.e. I controlled where I introduced the macros via #include.)
and
- adding a few somewhat 'higher-level' c++ methods below that include, this is the code which made use of the macros. These 'higher-level' c++ methods were declared in hpp, and defined in the cpp. Other code used these methods ... I suppose in some sense I 'wrapped' the macros.