Search code examples
c++clinkage

static and shared library and their cross linking


After reading a lot of threads, I am still confused regarding shared and static library and the way how they can be cross linked.

So my understanding is that when I have an executable that links to a static lib, the executable copies full contents of the functions/resources it needs into itself, so when it runs, it no longer needs the static lib. If the executable links to a shared lib, then it only create place holder for all the contents it needs, so when it runs, it needs the shared lib in the path, so it can loads the contents to the placeholder.

If the above statement is correct, then are the following correct?

  1. when I build a static library A that links to a shared lib B, and then build an executable C that links to A for functions that are originally from B. As a result, when I run C, I don't A to be presented because all needed contents are already in C, but B is still needed.
  2. when I build a shared library A that links to a static lib B, and then build an executable C that links to A for functions that are originally from B. As a result, when I run C, I only need Abut not B as all the contents needed is already in A.

Solution

  • when I have an executable that links to a static lib, the executable copies full contents of the functions/resources it needs into itself, so when it runs, it no longer needs the static lib

    Correct.

    If the executable links to a shared lib, then it only create place holder for all the contents it needs, so when it runs, it needs the shared lib in the path

    It needs access to the shared library, certainly. The rules by which the shared library is found varies by platform.

    when I build a static library A that links to a shared lib B, and then build an executable C that links to A for functions that are originally from B. As a result, when I run C, I don't A to be presented because all needed contents are already in C, but B is still needed.

    Correct

    when I build a shared library A that links to a static lib B, and then build an executable C that links to A for functions that are originally from B. As a result, when I run C, I only need A but not B as all the contents needed is already in A

    Correct

    Essentially, when you link against a static library, you never need it at runtime, and when you link against a shared library, you do.