【问题标题】:How to support two versions of third-party libraries with different namespaces in onecodebase如何在一个代码库中支持两个版本不同命名空间的第三方库
【发布时间】:2020-12-10 07:19:27
【问题描述】:

我有两个版本的第三方 C++ 库(lib.so 和头文件) 在一个版本中,所有类/枚举/结构都在命名空间“A”中 在另一个版本中,它们位于命名空间“B”中 两个版本的标头和 lib.so 名称相同

我怎样才能拥有相同的代码库,以便我可以同时支持这两个版本。像这样的

if (myVersion == "1.0") {
    /* pick all the symbols from namespace "A"*/
} else {
    /* pick all the symbols from namespace "B"*/
}

【问题讨论】:

  • 在运行时(在一个可执行文件中)或编译时支持这两个版本?

标签: c++ dll namespaces shared-libraries version


【解决方案1】:

您在代码中的建议是在运行时确定它,这在 C++ 中是不可能的。

如果您的版本是常量,您可以将其声明为宏并使用预处理器进行调节。

正如 cmets 中所说,不建议使用 using namespace,命名空间别名可能会更好。

#if VERSION == 1000 //...
namespace My = A;
#else
namespace My = B;
#endif

//使用我的::...

但是,如果你坚持使用using namespace

#define VERSION //your version

...

#if VERSION == 1000 //or something like that to mark 1.0.0.0
using namespace A;
#else
using namespace B;
#endif

【讨论】:

  • 您还可以确定哪个是“默认”并使用-Dmacroname 设置宏值,并仅使用#ifdef macroname 执行与此答案非常相似的操作并使用适当的命名空间
  • namespace alias 似乎比using namespace 更干净。
  • @user4581301 我没说它好,只是它是一个可选的解决方案。
  • @רועיאבידן 别介意我。我在诅咒自己的愚蠢。在那次编辑之后,我的观点现在没有实际意义。核爆我的 cmets。
  • 建议将最佳选项移至答案顶部。太多人没有读完答案就跑去尝试他们阅读的第一件事。
【解决方案2】:

使用下面的代码,我创建了两个包装器 .so(一个带有 version1 lib 和 -DVERSION=1,另一个带有 version2 lib 和 -DVERSION=2) 假设它们是 wlib1.so 和 wlib2.so

我将位于命名空间 A 或 B 中的 API(取决于我正在编译的内容)包装在 extern "C" 中

例如:

#define VERSION //your version

extern "C"
{
#if VERSION == 1 //or something like that to mark 1.0.0.0
using namespace A;
#else
using namespace B;
#endif
 void foo_wrapper() {
  foo();
  // wlib1.so will have A::foo() and wlib2.so will have B::foo()
}
}

现在在用户端,我在运行时使用了类似的东西:

using foo_t = void (*)();
foo_t foo_fp = nullptr;

void init(int ver)
{
std::string lib = "";
if (ver == 1) {
   lib = "wlib1.so";
} else {
   lib = "wlib2.so";
}

void* handle = dlopen(lib.c_str(), RTLD_LAZY);
foo_fp = reinterpret_cast<foo_t>(dlsym(handle, "foo_wrapper"));
}

/* use init(ver) before calling anything */
foo()
{
   foo_fp();
}

因此用户可以在运行时通过版本控制

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2013-01-15
    • 2017-03-01
    相关资源
    最近更新 更多