Handling macro redefinition without modifying .h files ... C / C++ language
- by user310119
Background:
Let assume that I have two header files a.h and b.h.
a.h contains:
#define VAR 1
b.h contains:
#define VAR 2
Note: The name of both of the macro is same.
Let say I have some file myFile.c which includes both of the header files i.e. a.h and b.h.
When I try to access VAR, I get a redefinition error of VAR.
In order to resolve this problem, I inserted #ifndef VAR statement in both a.h and b.h files to prevent this error.
a.h file becomes
#ifndef VAR
#define VAR 1
#endif
b.h file becomes
#ifndef VAR
#define VAR 2
#endif
Note: The header file can contain multiple macros, not just one macro.
Problem:
Let's assume that a.h and b.h files are obtained from third party library. These files don't contain #ifndef VAR statement.
I am not allowed to change their header files.
Can I resolve macro 'VAR' redefinition error in myFile.c or myFile.cpp file which uses VAR macro?
I know I #undef VAR can be used to undefine a macro VAR. How can I selectively include VAR later in my program? i.e. on line 10 of myFile.c code I should be able to refer to VAR definition from a.h file, on line 15 of my code I should be able to refer to VAR from b.h file and on line 18 again I should be able to refer to VAR from a.h file.
In short, am I able to do macro polymorphism ?
Given a name of header file, it should refer to macro definition present in that file.
I thought of using namespace trick to resolve an issue. Define first header file in namespace first and second header file in namespace second.
I tried defining two namespaces. First namespace contains #include a.h and second namespace contains b.h. However, namespace trick does not work with macro. When I tried to access firstns::VAR, compiler reports an error message.
Can you please suggest some way?