Macro definition conflict
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.
I have t开发者_如何学Cwo header files
test1.h
#define TEST 123
test2.h
#define TEST 456
Now I have a program included both these two headers, but I want my actually TEST to be 123. How can I avoid defining TEST as 456?
You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them. I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.
So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.
You can use the #ifdef
pre-processor directive to determine if TEST
is defined already for your particular case. Or just #undef
it first.
#undef TEST
#define TEST 123
Put that in your header file where you want TEST
to be 123 and not 456. Also, this needs to be before test1.h
.
#undef TEST
after the include of test2.h
and before the include of test1.h
. This is a bit of a hack though since you can't fix the macro names.
You can undefine it if you include both headers to your file as:
//yourfile.cpp
#include "test2.h" //include this before test1.h
#undef TEST //this undefines the macro defined in test2.h
#include "test1.h" //now this defines a macro called TEST which you need
#ifdef TEST
#undef TEST
#define TEST 123
#endif
Try this:
#include "test2.h"
#undef TEST
#include "test1.h"
This first includes test2, discards its TEST
and then includes test1.
精彩评论