静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么?

2021-12-25 00:00:00 dll linker c++ static-libraries

静态库、静态链接动态库和动态链接动态库的.lib文件里面是什么?

What is inside of a .lib file of Static library, Statically linked dynamic library and dynamically linked dynamic library?

为什么动态链接的动态库和静态链接中不需要 .lib 文件,.lib 文件只是一个包含所有方法的 .obj 文件.对吗?

How come there is no need for a .lib file in dynamically linked dynamic library and also that in static linking, the .lib file is nothing but a .obj file with all the methods. Is that correct?

推荐答案

对于静态库,.lib 文件包含该库的所有代码和数据.然后链接器识别它需要的位并将它们放入最终的可执行文件中.

For a static library, the .lib file contains all the code and data for the library. The linker then identifies the bits it needs and puts them in the final executable.

对于动态库,.lib 文件包含从库中导出的函数和数据元素的列表,以及它们来自哪个 DLL 的信息.当链接器构建最终的可执行文件时,如果使用了库中的任何函数或数据元素,则链接器会添加对 DLL 的引用(使其由 Windows 自动加载),并将条目添加到可执行文件的导入表中,以便对该函数的调用被重定向到该 DLL 中.

For a dynamic library, the .lib file contains a list of the exported functions and data elements from the library, and information about which DLL they came from. When the linker builds the final executable then if any of the functions or data elements from the library are used then the linker adds a reference to the DLL (causing it to be automatically loaded by Windows), and adds entries to the executable's import table so that a call to the function is redirected into that DLL.

您不需要 .lib 文件即可使用动态库,但如果没有,您就无法将 DLL 中的函数视为代码中的普通函数.相反,您必须手动调用 LoadLibrary 来加载 DLL(完成后调用 FreeLibrary),并调用 GetProcAddress 来获取函数的地址或 DLL 中的数据项.然后,您必须将返回的地址转换为适当的函数指针才能使用它.

You don't need a .lib file to use a dynamic library, but without one you cannot treat functions from the DLL as normal functions in your code. Instead you must manually call LoadLibrary to load the DLL (and FreeLibrary when you're done), and GetProcAddress to obtain the address of the function or data item in the DLL. You must then cast the returned address to an appropriate pointer-to-function in order to use it.

相关文章