c++ - 在同名的 C++ 顶级函数之间进行选择
问题描述
我的 C++ 项目huzzah
有一个include/huzzah.h
用于定义两个函数
do_this
和do_that
. 我在src/thing1.cpp
和中有这些功能的多个实现src/thing2.cpp
。鉴于以下单元测试,我如何指定使用函数的 do_this 或 do_that 实现?也许在huzzah/CMakeLists.txt
,或通过main
args?
#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 类。)
解决方案
您可以为每个 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的正确路径等等
推荐阅读
- python - 蟒蛇和BS4 | 获取具有特定文本内容的所有表格数据
- scala - 如何在每个条目的所有行条目上获得 scala-spark 中数组类型列的平均值?
- c# - 如何在 UWP 应用程序中向受信任的根证书颁发机构添加证书
- python - 从手机上的 API 获取信息时出错
- ios - 点击按钮后如何删除 SKNode?
- wso2 - 使用 WSO2 身份服务器在旧令牌到期后获取新访问令牌失败
- r - 在 navbarPage 的选项卡中重用 ouputs$xxx
- r - 在 R 中使用 lpsolve 最小化目标函数问题
- css - React Native Nativebase如何将Picker浮动到右侧
- python - 为什么一个值改变了,而第二个值没有?