我可以让 gcc 链接器创建静态库吗?
我有一个由大约 300 个 C++ 文件组成的库。
使用该库的程序不想动态链接到它。 (由于各种原因,但最好的一个是某些支持的平台不支持动态链接)
然后我使用g++和ar创建一个静态库(.a),这个文件包含所有这些文件的所有符号,包括图书馆不想导出。
我怀疑将使用程序与该库链接需要花费不必要的长时间,因为 .a 中的所有 .o 文件仍然需要解析其引用,并且链接器有更多符号需要处理。
创建动态库(.dylib / .so)时,您实际上可以使用链接器,它可以解析所有库内符号,并仅导出库想要导出的符号。然而,结果只能在运行时“链接”到消费程序中。
我想以某种方式获得动态链接的好处,但使用静态库。
如果我的谷歌搜索正确地认为这确实不可能,我很想了解为什么这是不可能的,因为它似乎是许多 C 和 C++ 程序可以从中受益的东西。
I have a library consisting of some 300 c++ files.
The program that consumes the library does not want to dynamically link to it. (For various reasons, but the best one is that some of the supported platforms do not support dynamic linking)
Then I use g++ and ar to create a static library (.a), this file contains all symbols of all those files, including ones that the library doesn't want to export.
I suspect linking the consuming program with this library takes an unnecessary long time, as all the .o files inside the .a still need to have their references resolved, and the linker has more symbols to process.
When creating a dynamic library (.dylib / .so) you can actually use a linker, which can resolve all intra-lib symbols, and export only those that the library wants to export. The result however can only be "linked" into the consuming program at runtime.
I would like to somehow get the benefits of dynamic linking, but use a static library.
If my google searches are correct in thinking this is indeed not possible, I would love to understand why this is not possible, as it seems like something that many c and c++ programs could benefit from.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
静态库只是存档(因此为“.a”),即 .o 文件的集合。就像 tar 存档一样,只是更加简单。由于 ar 不是链接器,因此不存在聚合(如“ld -r”所做的那样),因此不会消除库内符号。
这就是共享库最初被发明的原因,而且它们现在很常见,所以人们只是忽略了静态库的缺点。他们只是简单地通过“它编译?发布它。”。
Static libraries are just archives (hence ".a"), a collection of .o files. Like a tar archive, just even more plain. Since ar is not a linker, there is no conglomeration (as "ld -r" would do) and thus no intralibrary symbol elimination.
That's why shared libraries were invented in the first place, and they are pretty common now, so people just ignore the drawbacks of static libraries. They simply go by "it compiles? ship it.".
我还没有尝试或测试过这一点,但看起来
ld
执行增量或部分链接的能力可能正是您正在寻找的。检查--relocatable
选项(如果处理 C++,您可能还需要查看-Ur
选项)是否应用于将进入库的目标文件会做你想做的事。我认为您应该能够将该操作的输出用作程序的最终链接步骤的目标文件(或将其放在静态库本身中)。
I haven't tried or tested this, but it looks like
ld
's ability to perform incremental or partial linking might be what you're looking for. Check if the--relocatable
option (you might also need to look at the-Ur
option if dealing with C++) when applied to the object files that would go into the library will do what you want.I think you should then be able to use the output of that operation as an object file (or have it in a static library itself) for your program's final link step.