【发布时间】:2021-05-20 16:02:15
【问题描述】:
如果已安装共享库,我如何有条件地加载和使用它,但如果它不存在,我仍然可以在没有该功能的情况下运行?更具体地说,我可以在不将该库用作插件的情况下做到这一点吗?如果可能的话,我更喜欢在构建时而不是运行时失败。
如果我使用库标志 -lfoo 构建它,它就会构建。但随后它无法运行 libfoo.so.2 未安装在目标系统中。但如果我不添加库标志,则链接失败。
这里有一些代码片段以获得更好的图片。
myAdapter.cpp
#include "newlib/foo.h" //this is from the shared library
...
bool myAdapter::isAvailable()
{
handle_ = dlopen("libfoo.so.2", RTLD_LAZY);
if (!handle_)
{
return false;
}
return true;
}
...
bool myAdapter::init()
{
if (!isAvailable())
{
return false;
}
isInitilized = false;
isConnected = false;
if (!fooInit()) // shared library function
{
fooCleanup(); //shared library function
return false;
}
// these are my private functions but they call shared library functions.
if (!createUserParams_() || !setCallbacks_() || !createContext_() || !connect_())
{
return false;
}
return true;
}
...
myApp.cpp
#include "myAdapter.h"
...
int main()
{
...
foo = new myAdapter();
if (!foo.init())
{
cout << "Foo function is not available;
isFooAvailable = false;
}
}
...
}
【问题讨论】:
-
prefer failing during build time rather than runtime if possible. if I build it with the library flag -lfoo, it builds. But then it fails to run it libfoo.so.2 is not installed in the target system.如果不知道目标系统上是否安装了库,构建时怎么会失败? -
我已经在 init() 中添加了 isAvailable() 函数。所以,它在运行时不会走得更远。我只是想在构建期间尽可能多地检查。
-
无法再编辑我的答案,所以我在这里添加。我想检查我是否正确使用了库 API。此外,共享库有一堆内部结构和枚举,例如错误代码等。我也想利用这些。
-
这能回答你的问题吗? How to make a shared library delay loaded on Linux。该线程提到了一个帮助脚本项目来为库函数生成存根,这些函数将在首次访问时加载库 - github.com/yugr/Implib.so
标签: c++