我对DLL和LIB所知甚少,只知道它们包含程序正常运行所需的重要代码——库。但是为什么编译器要生成它们呢?将所有代码都包含在一个可执行文件中不是更容易吗?DLL和LIB之间的区别是什么?


当前回答

另一个方面是安全性(混淆)。一旦一段代码从主应用程序中提取出来并放入一个“分离的”动态链接库中,就更容易攻击和分析(反向工程)代码,因为它已经被隔离了。当同一段代码保存在LIB库中时,它是已编译(链接)的目标应用程序的一部分,因此很难将这段代码与其余的目标二进制文件隔离(区分)。

其他回答

DLL是在其他可执行程序之间共享的函数库。只要看看你的windows/system32目录,你就会找到几十个。当您的程序创建一个DLL时,它通常也会创建一个lib文件,以便应用程序*.exe程序可以解析DLL中声明的符号。

.lib是一个静态链接到程序的函数库——它们不被其他程序共享。与*链接的每个程序。Lib文件中有该文件中的所有代码。如果你有两个程序A.exe和B.exe链接到C.lib,那么每个A和B都将包含C.lib中的代码。

如何创建dll和库取决于所使用的编译器。每个编译器都是不同的。

另一个方面是安全性(混淆)。一旦一段代码从主应用程序中提取出来并放入一个“分离的”动态链接库中,就更容易攻击和分析(反向工程)代码,因为它已经被隔离了。当同一段代码保存在LIB库中时,它是已编译(链接)的目标应用程序的一部分,因此很难将这段代码与其余的目标二进制文件隔离(区分)。

有静态库(LIB)和动态库(DLL) -但请注意.LIB文件可以是静态库(包含目标文件)或导入库(包含允许链接器链接到DLL的符号)。

Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.

Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.

例如,几乎每个用“C”编写的程序都需要来自“C运行时库”的函数,尽管很少有程序需要所有这些函数。C运行时有静态和动态两种版本,因此您可以根据特定的需要确定程序使用哪个版本。

另一个区别在于性能。

由于DLL在运行时由.exe(s)加载,.exe(s)和DLL使用共享内存的概念,因此性能相对于静态链接较低。

另一方面,.lib是在编译时静态链接到每个请求进程的代码。因此.exe将只有一个内存,从而提高了进程的性能。

One important reason for creating a DLL/LIB rather than just compiling the code into an executable is reuse and relocation. The average Java or .NET application (for example) will most likely use several 3rd party (or framework) libraries. It is much easier and faster to just compile against a pre-built library, rather than having to compile all of the 3rd party code into your application. Compiling your code into libraries also encourages good design practices, e.g. designing your classes to be used in different types of applications.