dllshared-librariesstatic-linkingdynamic-linking

Why is linking a dynamic library against a static library apparently easy on Windows but on Linux `-fPIC` makes that difficult?


I am working on adapting an existing ODBC driver so that it can target Linux.

ODBC Drivers are generally distributed as DLLs on Windows and shared objects (.so) on Linux.

The driver depends on Boost. On Windows, we've always linked against the static (.lib) library without any special issue!

However, if we want to statically link our Linux .so file against the static (.a) library, we find we need to rebuild Boost with -fPIC (distributed static library binaries are generally NOT compiled with -fPIC).

Why is there this extra complication on Linux but not on Windows?

Does Windows always build its static libraries as "position independent code" unlike Linux?

I have found several questions somewhat related to this topic, but cannot find any that directly address why there's a difference on Linux and on Windows

Example: Linking Boost static libraries


Solution

  • Why is there this extra complication on Linux but not on Windows?

    Because Windows compilers create -fPIC code by default, and UNIX compilers usually don't.

    Using -fPIC results in slightly slower and slightly larger code, and for a significant period of UNIX history there was no support for shared libraries at all, so when that support did finally materialize, there was little reason to change the default and pessimize all existing binaries.

    On Windows, we've always linked against the static (.lib) library

    Contrary to what you may believe, linking on Windows against .lib does not necessarily mean that you are linking against a static library. The foo.lib may simply be an import library for foo.dll.