静态链接库与动态链接库(ps:在ubuntu下叫共享库)之间的区别?
动态链接库是.so文件(在windows下是.dll 或者在OS X 下是.dylib)。所有跟这个库相关的代码都在这个文件中(ps:要用这个库,就是要调用的接口在这个库中,而这些接口相关的所有源代码都被编译到了这个库中)。调用了库中接口的程序中有对该库的引用。一个使用了动态链接库的程序仅仅把对这个动态链接库的引用编译到目标码中。
静态链接库是.a文件(或者在 Windows中是.lib文件)。所有跟这个库相关的代码都在这个文件中。编译的时候,调用的接口涉及的代码直接被编译到程序中,一个使用了静态链接库的程序直接将使用的静态库的代码拷贝到程序中。[windows中有部分lib文件用于对dll文件做引用,但是这些lib的使用机制和动态库一样。]
每一种链接方法都有利有弊:
动态链接库
优点:
1. 让编译后的目标文件比较小,因为不用每一次使用都复制一份。
2. 动态链接库允许在不用重新编译的情况下更换(升级)使用的动态链接库,只要更换前后的接口保持一直就行。
3. 由于动态库可以在运行时被程序载入,这样可以实现一个二进制插件系统(二进制插件系统的运行机制就是运行时载入插件)
缺点:
在运行时加载需要的函数以及变量需要额外的一些开销(开销比较小)
静态链接库
缺点:
增加了所有使用改库的程序编译后的目标文件
优点:
1. 因为需要的代码都在编译的时候拷贝到目标文件中了,在做程序移植的时候不需要环境里有这些库。
2. 没有额外运行时的载入开销。
就我个人而言,我更喜欢共享库,但在编译的目标文件中有许多可能难以满足的外部依赖项(比如c++标准库的特定版本或Boost c++库的特定版本)时,使用静态库。
原文:
What is the difference between static and shared libraries?
Shared libraries are .so (or in Windows .dll, or in OS X .dylib)
files. All the code relating to the library is in this file, and it is
referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared
library.Static libraries are .a (or in Windows .lib) files. All the code
relating to the library is in this file, and it is directly linked
into the program at compile time. A program using a static library
takes copies of the code that it uses from the static library and
makes it part of the program. [Windows also has .lib files which are
used to reference .dll files, but they act the same way as the first
one].There are advantages and disadvantages in each method.
Shared libraries reduce the amount of code that is duplicated in each
program that makes use of the library, keeping the binaries small. It
also allows you to replace the shared object with one that is
functionally equivalent, but may have added performance benefits
without needing to recompile the program that makes use of it. Shared
libraries will, however have a small additional cost for the execution
of the functions as well as a run-time loading cost as all the symbols
in the library need to be connected to the things they use.
Additionally, shared libraries can be loaded into an application at
run-time, which is the general mechanism for implementing binary
plug-in systems.Static libraries increase the overall size of the binary, but it means
that you don’t need to carry along a copy of the library that is being
used. As the code is connected at compile time there are not any
additional run-time loading costs. The code is simply there.Personally, I prefer shared libraries, but use static libraries when
needing to ensure that the binary does not have many external
dependencies that may be difficult to meet, such as specific versions
of the C++ standard library or specific versions of the Boost C++
library.