I have two libraries (third-party), and wi开发者_开发百科thin each of these libs they have defined two classes with same name (in header files).
// Lib A, HeaderA.h
struct mycompare
{
//Some code
};
// Lib B, HeaderB.h
struct mycompare
{
//Same code
};
Please note that, in both libs, mycompare name and the implementation is same. How to use both header files same time ?
Assuming you can't edit the headers/libraries:
- indirection: create your own out-of-line wrapper for the simpler of A and B, which includes HeaderA.h or HeaderB.h only in the implementation.
- this is similar to but much less work and coupling than Als's option 2 ;-)
- shameless hackery: include HeaderA.h, then
#define mycompare mycompare_duplicate
before including HeaderB.h, then#undef mycompare
. This could bite you if one of the implementations later changes, and may not be possible if the header later uses the symbol itself (e.g. as a function argument, where type name-mangling would differ and prevent your calls being resolved).
If you can edit the libraries, then obviously the best long-term option is to put their functionality into separate namespaces.
A quick workaround is to simply wrap them in a namespace. That might be simple enough, depending on how complicated the headers are. Alternatively, consider writing your own header with this particular struct (if you know it's going to stay the same) and cast when passing to each of them.
That said, it's highly untypical to have this case. Are you sure that library B is not dependent on A or vice versa? In that case, the only thing that might be broken is some #define USE_EXTERNAL_A
or so. A typical example are libraries that include zlib unless you provide them with one.
Just make a third header, move redundant definitions in it(only once); then include this header into the originals. It should work.
精彩评论