C/C++。库相对于组合目标文件的优点
虽然在库中组合多个目标文件很常见,但也可以(至少在 Linux 中)将多个目标文件组合到另一个目标文件中。
(参见组合两个GCC编译的.o对象文件到第三个 .o 文件)
由于使用库而不是仅组合对象文件有缺点:
1:链接时仅使用一种类型的文件(对象)更容易,特别是如果所有文件都做同样的事情。
2:链接时(至少在GCC中),库(默认情况下)需要排序并且无法处理循环依赖。
我想知道图书馆有什么优势(除了第 22 条军规,它们被大量使用)。
经过一段时间的搜索后,我得到的唯一解释似乎是单个库比多个目标文件更好。
While it is commonplace to combine multiple object files in a library, it is possible (at least in Linux) to combine multiple object files into another object file.
(See combine two GCC compiled .o object files into a third .o file)
As there are downsides to using libraries instead of just combined object files:
1: It's easier to work with only one type of file (object) when linking, especially if all files do the same thing.
2: When linking (At least in GCC), libraries (by default) need to be ordered and can't handle cyclic dependencies.
I want to know what advantages there are to libraries (apart from the catch 22 that they're used lots).
After searching for a while, the only explanation I get seems to be that single libraries are better than multiple object files.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然这取决于所使用的链接器,但目标文件完整地包含在最终的二进制文件中。因此,如果将多个目标文件合并为一个目标文件,则生成的(组合的)目标文件将包含在生成的二进制文件中。
相反,库就是目标文件的库。链接器只会从库中提取解析所有符号链接所需的目标文件。如果不需要目标文件(在库中),则它不会包含在二进制文件中。
While it depends on the linker being used, object files are being included in the final binary in their entirety. So, if you combine several object files into one object file, then the resulting (combined) object file is included in the resultant binary.
In contrast, a library is just that, a library of object files. The linker will only pull the object files from the library that it needs to resolve all the symbolic links. If an object file (in the library) is not needed, then it is not included int the binary.
一般来说,库更好,因为链接器可以优化库中未使用的 .o 文件。
以某种方式组合这些文件也有一些优点:
Generally library is better since linker can optimize out unused .o files in library.
Combining the files somehow has some advantages too:
原因之一是
.a
库中的对象只会被拉入以满足未定义符号引用 - 因此,如果您希望允许调用应用程序定义一个符号,或者在“库”代码中使用默认定义,可以使用真正的库来执行此操作,但不能使用单个.o
文件。One reason is that objects in a
.a
library will only be pulled in to satisfy undefined symbol references - so if you want to allow the possibility for the calling application to define a symbol, or use a default definition in the "library" code, it's possible to do this with a real library but not with a single.o
file.如果您使用目标文件,则目标文件中的所有代码都将放置在您的应用程序中。如果您使用库,则只有所需的代码。
If you use object files, then all the code in the object file is placed in your application. If you use libraries, then only the required code is.