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

Sulla picture Sulla · Jul 14, 2010 · Viewed 63.7k times · Source

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

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?

Answer

Anthony Williams picture Anthony Williams · Jul 15, 2010

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.

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.

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.