首页 > 解决方案 > 在同名的 C++ 顶级函数之间进行选择

问题描述

我的 C++ 项目huzzah 有一个include/huzzah.h用于定义两个函数 do_thisdo_that. 我在src/thing1.cpp和中有这些功能的多个实现src/thing2.cpp。鉴于以下单元测试,我如何指定使用函数的 do_this 或 do_that 实现?也许在huzzah/CMakeLists.txt,或通过mainargs?

#include "huzzah.h"

int main(int argc, char **argv) {
    auto a = do_this;
    auto b = do_that;
    std::cout << "a = " << a << std::endl;
    std::cout << "b = " << b << std::endl;
}

(我不想把它们变成 Thing1 和 Thing2 类。)

标签: c++

解决方案


您可以为每个 cpp 文件(在 cmake 中)创建 2 个共享库:

add_library(thing1 SHARED src/thing1.cpp)
add_library(thing2 SHARED src/thing2.cpp)

然后使用 dlopen/dlsym 动态加载它们(不要将您的应用程序与这些库链接):

using do_this_f = decltype(&do_this);

auto handle = dlopen( "libthing1.so", RTLD_LAZY );
auto do_this_1 = reinterpret_cast<do_this_f>( dlsym( handle, "do_this" ) );
do_this_1(); // calling do_this from libthing1.so

当然你需要添加错误处理,lib的正确路径等等


推荐阅读