Search code examples
c++linkerstatic-linkingsconsdynamic-linking

Does anything happen at build time that is specific to static linking


I tried to statically link some built libraries using the static option in the linker. I'm using SCons to compile/link the libraries. I was under the impression that static builds happen at link time, and therefore it did not matter what you were linking. I got a bunch of errors and was wondering if there is any difference between .o files that were destined to be statically linked to the libraries and .o files that were destined to be dynamically linked to the libraries. Theoretically, should these be the same?


Solution

  • In the general case you can't use static and dynamic libraries interchangeably. See: Static link of shared library function in gcc

    Regarding your actual question:

    ... if there is any difference between .o files that were destined to be statically linked to the libraries and .o files that were destined to be dynamically linked to the libraries. Theoretically, should these be the same?

    No, they should not be the same. There are differences, the most notable one probably being that a dynamic library has a non-empty .dynsym section.

    If a function foo() is linked statically into an application, then the functions defintion is going to be at a fixed (static!) location relative to the rest of the applications code.

    On the other hand, if we link foo() dynamically into our application, then at compile-time the application can't know where it can find the definition of foo() during execution, since the application can't make any assumptions about the library - not about the librarys location at runtime nor about its internal structure. Therefore, the library itself provides a section .dynsym in order for the client-code to be able to find foos definition although it wasn't clear at complie-time where this was going to be.