Shared Libraries (-fPIC)
A shared library (.so on Linux, .dylib on macOS, .dll on Windows) is linked into a program at run time, not build time. The executable only records "I need libgreet.so"; when the program starts, the dynamic loader (ld-linux-x86-64.so.2) finds the library, maps it into memory and connects the calls. One copy of the library on disk (and in memory) serves every program that uses it, and fixing a bug in the library fixes all of them without relinking.
Position-independent code
A shared library can be loaded at any address, a different one in every process. Its code must therefore work wherever it lands: position-independent code (PIC), compiled with -fPIC. Leave the flag out and the linker refuses when your code touches a global variable in the usual way:
mkdir -p so && cd so
cat > counter.c <<'SRC'
int counter_total = 0;
int counter_add(int n) { counter_total += n; return counter_total; }
SRC
gcc -c -fno-pic counter.c -o counter-nopic.o
gcc -shared counter-nopic.o -o libcounter.so
echo "--- with -fPIC"
gcc -c -fPIC counter.c -o counter.o
gcc -shared counter.o -o libcounter.so && file libcounter.so | cut -d, -f1-2/usr/bin/ld: counter-nopic.o: warning: relocation against `counter_total' in read-only section `.text'
/usr/bin/ld: counter-nopic.o: relocation R_X86_64_PC32 against symbol `counter_total' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status
--- with -fPIC
libcounter.so: ELF 64-bit LSB shared object, x86-64
The -fno-pic object uses an absolute address for counter_total, which only works if the library is loaded at one fixed place. With -fPIC the compiler accesses globals through the Global Offset Table (GOT), a table of addresses the loader fills in, and calls functions in other libraries through the Procedure Linkage Table (PLT). Ubuntu's GCC already produces position-independent executables by default (-fPIE), which is why the error needed -fno-pic to show up. Other compilers and older systems don't default to it: always pass -fPIC for library objects explicitly. CMake does that for you (POSITION_INDEPENDENT_CODE), as you will see in Modern CMake.
Linking against a shared library
mkdir -p so && cd so
cat > greet.c <<'SRC'
#include <stdio.h>
void greet(const char *who) { printf("Hello, %s! (from libgreet v1)\n", who); }
SRC
cat > main.c <<'SRC'
void greet(const char *who);
int main(void) { greet("shared world"); return 0; }
SRC
gcc -fPIC -c greet.c && gcc -shared greet.o -o libgreet.so
gcc -c main.c && gcc main.o -L. -lgreet -o app
readelf -d app | grep NEEDED
./app
echo "--- with LD_LIBRARY_PATH"
LD_LIBRARY_PATH=. ./app 0x0000000000000001 (NEEDED) Shared library: [libgreet.so]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
./app: error while loading shared libraries: libgreet.so: cannot open shared object file: No such file or directory
--- with LD_LIBRARY_PATH
Hello, shared world! (from libgreet v1)
The link worked, because -L. told the linker where to look. But -L means nothing at run time: the loader searches its own list (paths stored in the executable, LD_LIBRARY_PATH, the cache built by ldconfig from /etc/ld.so.conf, then /lib and /usr/lib). Our directory is in none of them. LD_LIBRARY_PATH=. adds it for one run. The next lesson, Sonames, rpath & the Loader, shows the permanent fixes.
readelf -d shows the dynamic section, the executable's instructions to the loader. Each NEEDED entry is a library to load.
Updating the library without relinking
The point of shared libraries: rebuild only the library, and existing programs pick up the change at their next start.
mkdir -p so && cd so
printf '#include <stdio.h>\nvoid greet(const char *w) { printf("Hello, %%s! (v1)\\n", w); }\n' > greet.c
printf 'void greet(const char *);\nint main(void) { greet("app"); return 0; }\n' > main.c
gcc -fPIC -shared greet.c -o libgreet.so
gcc main.c -L. -lgreet -o app
LD_LIBRARY_PATH=. ./app
printf '#include <stdio.h>\nvoid greet(const char *w) { printf("Hi there, %%s! (v2)\\n", w); }\n' > greet.c
gcc -fPIC -shared greet.c -o libgreet.so
LD_LIBRARY_PATH=. ./appHello, app! (v1)
Hi there, app! (v2)
app was not rebuilt, yet it now prints the v2 message. The same mechanism is a hazard: if v2 had changed greet's parameters, app would still call it the old way and misbehave at run time. Changing what a library exports, or how, is an ABI (application binary interface) change, which is what sonames and version numbers protect against.
What a library exports
Every global symbol in a shared library is exported by default, even internal helpers. nm -D lists the dynamic symbol table, the part the loader sees. Compiling with -fvisibility=hidden and marking the public API explicitly keeps the export list small, which speeds up loading and stops other code from depending on your internals:
mkdir -p vis && cd vis
cat > api.c <<'SRC'
#define API __attribute__((visibility("default")))
int helper_scale(int x) { return x * 3; }
API int api_compute(int x) { return helper_scale(x) + 1; }
SRC
gcc -fPIC -shared api.c -o libdefault.so
gcc -fPIC -shared -fvisibility=hidden api.c -o libhidden.so
echo "--- default visibility"
nm -D --defined-only libdefault.so | awk '{print $3}'
echo "--- -fvisibility=hidden"
nm -D --defined-only libhidden.so | awk '{print $3}'--- default visibility
api_compute
helper_scale
--- -fvisibility=hidden
api_compute
On Windows the default is the opposite: nothing is exported from a DLL unless you mark it (see Windows DLLs & Import Libraries). Hidden by default on Linux makes a library behave the same way on both platforms.
Static or shared?
| Question | Static .a |
Shared .so |
|---|---|---|
| When is code copied? | at link time, into each executable | never; loaded at run time |
Needs -fPIC? |
no (but harmless) | yes |
| Fix a bug in the library | relink every program | replace the .so |
| Risk | larger binaries, duplicated code | missing or incompatible .so at run time ("DLL hell") |
| Typical use | small utilities, single-file deployment, internal libraries | system libraries, plugins, large shared frameworks |
Test yourself
Why must objects in a shared library be compiled with -fPIC?
- For faster compilation
- The library can be loaded at any address, so its code must not depend on a fixed address
- To enable debugging
- To make it static
The program links with -L. -lgreet but fails to start with 'cannot open shared object file'. Why?
- The library is corrupt
-Lonly guides the linker; the run-time loader has its own search path- The program needs
-static -lwas misspelled
What does -fvisibility=hidden change?
- It strips debug info
- Symbols are not exported unless marked
visibility("default") - It hides the library from
ldd - It encrypts the library