Reputation: 73
Suppose I have this:
// test.h
namespace test {
#define TEST_DEBUG !NDEBUG
class TestClass {
#if TEST_DEBUG
// ...
#endif
};
}
The problem is that other files that include test.h
will also get the TEST_DEBUG
macro, which is not ideal.
If I use #undef
at the end of the header, then that means I can't use the macro in test.cpp
.
What would be the best way to solve this issue?
Upvotes: 0
Views: 434
Reputation: 667
Although I'd advise avoiding macros in C++ (eg this could be replaced with a bool parameter to the function), the simplest way to achieve this is to define TEST_DEBUG in test.cpp before including test.h, and removing it from test.h.
A #include directive is replaced by the c preprocessor similar to a "copy the contents of that file here" way. This copy is repeated each time the #include appears. This also means if there's something defined before the #include appears in one file, but that's not defined in another, then things may break in unpredictable ways (because eg one file thinks an object is bigger than another file thinks it is).
However, to give more idiomatic c++, for a compile time flag you can use bool constexprs. Alternatively, for a runtime change, if it's a class, pass a bool to the constructor to indicate the difference, a function can have an extra parameter that defaults to false, etc.
Upvotes: 3