Search code examples
cdllstatic-linkingdynamic-library

Can we link a dynamic C library statically?


We know that when linking a static library, the linker copies the relevant code from .a file to the executable binary file. And when linking a dynamic library, the linker just copies the addresses of functions it found in .lib file (under Windows) into the binary file, and the functions themselves are not copied. At runtime, the OS loads the dll, and the program runs the code according to the addresses. The question is, could I use the .lib file and dll to link the dynamic library statically? The linker reads addresses from the .lib, and then copies relevant code from the dll to binary file. It should work, right?


Solution

  • I have no clue whether your idea could work, but do note that -- on Windows, with Visual Studio at least -- a static library is something very different from a DLL.

    With VS, a static library is basically just an object file container, that is, you have a .lib file, but that .lib file is just a container for all the .obj files that the compiler produced for the project.

    The important thing here is that the .objcode in the static library hasn't gone through the linking stage yet, no linker has been involved.

    Whereas the DLL is (finally) produced by the linker (from object files).

    So the question here is really one of toolchain support, since the DLL is already a linker output, I doubt you could get the linker to re-link its PE code directly into the executable.