如何链接到运行时可能不存在的目录?
我正在为 Linux 编写一个库,它的一些功能依赖于共享库 libfoo.so。
我正在尝试考虑 libfoo.so 不存在的情况。对于这种情况,我有一个明确定义的行为,但我不知道如何在链接方面正确实现它。
目前,我的库是针对 libfoo.so 进行编译的,当客户端尝试在不包含 libfoo.so 的环境中对其代码进行编译时,他会收到链接错误。
我的问题是,如何构建我的库,即使 libfoo.so 不存在,它也能编译,但行为不同。我自己能想到的唯一解决方案是从它分支一个不支持 foo 的版本,但必须有更好的方法...
提前感谢
由于给定的答案而进行的跟进: 似乎不链接 libfoo 而是使用 dlopen 动态加载它解决了问题,但它需要我手动导出所有符号,并且范围有限......是否有任何“不那么痛苦”来实现这一点?
I'm writing a library for Linux which has some functionality which relies on the a shared library libfoo.so.
I'm trying to case where libfoo.so doesn't exist into consideration. I have a well defined behavior for such a case, but I don't know how to properly implement it, linkage wise.
Currently, my library is shipped compiled against libfoo.so, when a client tries to compile it's code against it on an environment which doesn't include libfoo.so he gets linkage errors.
My question is, how can I build my library in such a way that it would compile even if libfoo.so doesn't exist, but behave differently. The only solution I was able to come up with myself is to branch from it a version which doesn't support foo, but there must be a better way...
Thanks in advance
A follow up due to the given answer:
It seems that not linking against libfoo but rather dynamically loading it with dlopen solves the problem, but it requires me to manually export all the symbols, and is limited in scope... Is there any "less painful" to achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两个不同的问题符合描述,具体取决于是在编译时还是在运行时检测库的存在。
在编译时,您必须使用某种工具来检测库是否存在并修改构建脚本以将该信息传递给代码(认为定义)。
在运行时,您可以避免链接库,而是动态加载它。代码应该处理定位/加载库的失败并回退到替代版本。
There are two different problems that kind of fit the description, depending on whether the presence of the library is to be detected at compile time or at runtime.
At compile time you will have to use some tool to detect whether the library is present and modify the build scripts to pass that information down to the code (think defines).
At runtime, you can avoid linking against the library, and rather dynamically load it. The code should handle failures to locate/load the library and fall back to the alternative version.