如何链接到运行时可能不存在的目录?

发布于 2024-12-09 06:43:31 字数 411 浏览 0 评论 0原文

我正在为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久隐师 2024-12-16 06:43:31

有两个不同的问题符合描述,具体取决于是在编译时还是在运行时检测库的存在。

在编译时,您必须使用某种工具来检测库是否存在并修改构建脚本以将该信息传递给代码(认为定义)。

在运行时,您可以避免链接库,而是动态加载它。代码应该处理定位/加载库的失败并回退到替代版本。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文