To answer your questions one by one:
-
Dynamic linking defers part of the linking process to runtime.
It can be used in two ways: implicitly and explicitly.
Implicitly, the static linker will insert information into the
executable which will cause the library to load and resolve the
necessary symbols. Explicitly, you must callLoadLibrary
or
dlopen
manually, and thenGetProcAddress
/dlsym
for each
symbol you need to use. Implicit loading is used for things
like the system library, where the implementation will depend on
the version of the system, but the interface is guaranteed.
Explicit loading is used for things like plug-ins, where the
library to be loaded will be determined at runtime. -
The
.lib
file is only necessary for implicit loading. It
contains the information that the library actually provides this
symbol, so the linker won’t complain that the symbol is
undefined, and it tells the linker in what library the symbols
are located, so it can insert the necessary information to cause
this library to automatically be loaded. All the header files
tell the compiler is that the symbols will exist, somewhere; the
linker needs the.lib
to know where. -
Under Unix, all of the information is extracted from the
.so
. Why Windows requires two separate files, rather than
putting all of the information in one file, I don’t know; it’s
actually duplicating most of the information, since the
information needed in the.lib
is also needed in the.dll
.
(Perhaps licensing issues. You can distribute your program with
the.dll
, but no one can link against the libraries unless
they have a.lib
.)
The main thing to retain is that if you want implicit loading,
you have to provide the linker with the appropriate information,
either with a .lib
or a .so
file, so that it can insert that
information into the executable. And that if you want explicit
loading, you can’t refer to any of the symbols in the library
directly; you have to call GetProcAddress
/dlsym
to get their
addresses yourself (and do some funny casting to use them).