在编程中,库是可以在程序中重用的预编译代码段的集合。库简化了程序员的生活,因为它们提供了可重用的函数、例程、类、数据结构等
它们可以在程序中重复使用。
静态库:静态库或静态链接库是一组例程、外部函数和变量,它们在编译时在调用者中解析,并由编译器、链接器或绑定器复制到目标应用程序中,生成目标文件和一个独立的可执行文件。这个可执行文件和编译它的过程都被称为程序的静态构建。从历史上看,库只能是静态的。
它们通常比共享库更快,因为一组常用的目标文件被放入单个库可执行文件中。可以构建多个可执行文件而无需重新编译文件。因为它是要构建的单个文件,所以链接命令的使用比共享库链接命令简单,因为您指定了静态库的名称。
共享库:
共享库是 .so(或在 Windows .dll 中,或在 OS X .dylib 中)文件。
这些是动态链接的,仅包括库的地址(而静态链接是浪费空间)。动态链接在运行时链接库。因此,所有的函数都在内存空间中的一个特殊位置,每个程序都可以访问它们,而无需它们的多个副本。
properties | Static library | Shared library |
---|---|---|
Linking time | It happens as the last step of the compilation process. After the program is placed in the memory | Shared libraries are added during linking process when executable file and libraries are added to the memory. |
Means | Performed by linkers | Performed by operating System |
Size | Static libraries are much bigger in size, because external programs are built in the executable file. | Dynamic libraries are much smaller, because there is only one copy of dynamic library that is kept in memory. |
External file changes | Executable file will have to be recompiled if any changes were applied to external files. | In shared libraries, no need to recompile the executable. |
Time | Takes longer to execute, because loading into the memory happens every time while executing. | It is faster because shared library code is already in the memory. |
Compatibility | Never has compatibility issue, since all code is in one executable module. | Programs are dependent on having a compatible library. Dependent program will not work if library gets removed from the system . |
想要从精选的视频和练习题中学习,请查看 C 基础到高级C 基础课程。