Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve class-name conflicts between two third-party libraries that do not use namespaces?

Tags:

c++

namespaces

My project uses two third-party open-source libraries, both libraries define type BDD, and both do not use namespaces.

Is there a way to resolve the name conflict? Maybe force one library into a custom namespace?

Additional info: the first library uses BDD only as type alias (typedef int BDD), so it does not call any methods on BDD.

like image 801
Ayrat Avatar asked Jan 29 '23 02:01

Ayrat


1 Answers

Since one of your libraries only uses BDD as an alias for int (I'll assume this library is called lib1, and the other lib2), you can just change the name of this alias by telling the preprocessor to rename it before including the library, like so:

#define BDD BDD_lib1
#include <lib1>
#undef BDD

#include <lib2>

If you ever need to use the name BDD from lib1 in your code, you can then reference it with BDD_lib1 (or just with int if you're not worried that its type can change in a future version of lib1).


However, I would consider this approach only a workaround, and not a true solution, so you may want to consider doing as @YSC suggested in his answer and provide a patch so other people trying to use the libraries do not run into the same problem.


Does this work in a more general scenario?

If BDD was not just a simple type alias, but a separate class, one could run into trouble due to C++'s name mangling, so this method would only work if the name BDD is not important in any scenarios where name mangling would appear. This imposes more or less the following restrictions:

  • BDD must not have any non-inline methods
  • any types depending on BDD (e.g. a specialization A<BDD> of class template template <typename> class A; is a type depending on `BDD) must not have any non-inline methods
  • all functions/methods whose argument list includes types depending on BDD must either be inline, or have C linkage
like image 65
gflegar Avatar answered Feb 05 '23 23:02

gflegar