为什么静态和动态可链接库不同? [英] Why are static and dynamic linkable libraries different?

查看:96
本文介绍了为什么静态和动态可链接库不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它们都包含编译后的代码,为什么我们不能在运行时加载静态"文件,为什么不能在编译时与动态库链接?为什么需要使用单独的格式来包含独立"代码?有什么需要保证区别的地方要存储什么?

If both of them contain compiled code, why can't we load the "static" files at runtime and why can't we link with the dynamic libraries at compile time? Why is there a need for separate formats to contain "standalone" code? What needs to be stored in either one that warrants the difference?

推荐答案

静态库在包含对象文件库的意义上是真正的库.每个目标文件通常是从单个源文件创建的,并且包含机器代码以及有关代码所需数据的信息.在链接步骤中,链接器将选择必要的目标文件并将其组合为可执行文件.

Static libraries are true libraries in the sense that they contain a library of object files. Each object file is often created from a single source file and contains machine code as well as information about data required for the code. During the link step the linker will pick the necessary object files and combine them into an executable.

机器码的一个重要部分是跳转,调用和数据指针必须包含实际的内存地址.但是,如果目标文件需要调用另一个目标文件中的另一个函数,则只能使用符号来引用该函数.当链接程序将目标文件组合为可执行代码时,符号引用将被解析并转换为实存储器地址.

One important part of machine code is that jumps, calls and data pointers will have to contain real memory addresses. However, if an object file needs to call another function in another object file it can only refer to that function using a symbol. When the linker combines the object files into executable code the symbol references are resolved and turned into real memory addresses.

动态库是可执行代码,可以将其加载到内存中并立即执行.在某些操作系统上,可能还有一个附加步骤,其中通过将可执行代码移动到另一个位置来重新编码代码,这需要将代码内的所有绝对地址移位固定量.此操作仍然比合并目标文件和解析链接器完成的符号要快得多.

A dynamic library is executable code that can be loaded into the memory and executed straight away. On some operating systems there may be an additional step where the code is rebased by moving the executable code to another location and this requires all absolute addresses within the code to be shifted by a fixed amount. This operation is still much faster than combining object files and resolving symbols done by the linker.

总结一下:

  • 静态库包含一些可执行代码,这些可执行代码使用符号来引用其他可执行代码
  • 动态库(和可执行文件)包含现在放置在固定位置的可执行代码,使符号可以替换为真实的内存地址

如果您曾经尝试链接大小合理的项目,您会注意到它花费的时间不短,可能比您等待启动应用程序的时间更长.这种解释说明了为什么您不能执行静态库.动态库已经过优化和剥离,除可执行代码外不包含任何内容,这使它们不适合用作静态库.

If you've ever tried to link a reasonably sized project you will have noticed that it takes a non-trivial amount of time, probably longer than you would like to wait to start an application. That sort of explains why you can't execute static libraries. And dynamic libraries have been optimized and stripped to not contain anything except executable code which makes them unsuitable for use as static libraries.

这篇关于为什么静态和动态可链接库不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆