The Complete Guide to Static and Shared Libraries in C
Build static and shared libraries in C with ar, gcc and ld, then link, version, install and debug them, with a decision table for choosing between the two.

Every C program of any size is split across files, and sooner or later part of it needs to be shared: between programs, between teams, or between a program and its plugins. A library is the unit of that sharing, and C gives you two kinds with very different behavior. A static library is a bundle of object files that the linker copies from at build time. A shared library is a file the program finds and loads at run time, and many programs can use one copy. Most trouble with libraries comes from not knowing which kind you have, what the linker did with it and where the loader will look. This guide builds one small library both ways, links programs against each, and then follows the questions that come up in practice: why argument order matters, how a program finds its libraries, how to version and hide symbols, how to install and package, and how to choose between static and shared. It uses GCC 14, GNU binutils 2.42 and glibc 2.39 on Linux x86-64. The tools are documented in the GCC link options, the ld manual and the ld.so manual page. For the file format underneath, see the complete guide to the ELF file format.
The short version: use a static library when you want one self-contained file and a small, stable dependency, and a shared library when many programs use the same code or when you need to fix it without rebuilding them. Everything below is the detail behind that sentence.
The project we will build
One library, three source files, and a program that uses it. The library is a small collection of statistics helpers, small enough to read and big enough to have structure:
#ifndef STATS_H
#define STATS_H
#include <stddef.h>
double stats_mean(const double *v, size_t n);
double stats_variance(const double *v, size_t n);
double stats_max(const double *v, size_t n);
#endif#include "stats.h"
double stats_mean(const double *v, size_t n)
{
double sum = 0;
for (size_t i = 0; i < n; i++) {
sum += v[i];
}
return n ? sum / (double)n : 0.0;
}#include "stats.h"
double stats_variance(const double *v, size_t n)
{
double m = stats_mean(v, n);
double acc = 0;
for (size_t i = 0; i < n; i++) {
acc += (v[i] - m) * (v[i] - m);
}
return n ? acc / (double)n : 0.0;
}#include "stats.h"
double stats_max(const double *v, size_t n)
{
double best = n ? v[0] : 0.0;
for (size_t i = 1; i < n; i++) {
if (v[i] > best) {
best = v[i];
}
}
return best;
}#include <stdio.h>
#include "stats.h"
int main(void)
{
double data[] = {2, 4, 4, 4, 5, 5, 7, 9};
size_t n = sizeof data / sizeof data[0];
printf("mean=%.2f variance=%.2f\n", stats_mean(data, n), stats_variance(data, n));
return 0;
}The program uses stats_mean and stats_variance and never calls stats_max. That detail pays off later when we look at what the linker copies. Compile every library source to an object file first, with warnings on:
gcc -O2 -Wall -Wextra -c mean.c variance.c max.c
ls *.omax.o mean.o variance.oStatic libraries: an archive of objects
A static library is an archive, a single file holding copies of object files with an index of the symbols they define. The tool is ar. By convention the file is named lib plus a name plus .a:
ar rcs libstats.a mean.o variance.o max.o
ar t libstats.a
nm -s libstats.a | head -8mean.o
variance.o
max.o
Archive index:
stats_mean in mean.o
stats_variance in variance.o
stats_max in max.oThe r flag inserts members, c creates the archive quietly and s writes the index. Link the program against it, either naming the file or using the search form:
gcc -O2 main.c -L. -lstats -o stats_static
./stats_staticmean=5.00 variance=4.00-L. adds the current directory to the library search path and -lstats asks for libstats. Because the program was linked against an archive, the code it needs was copied into the executable. You can delete libstats.a and the program still runs.
The linker took only what it needed. It started with main.o, saw two undefined symbols, stats_mean and stats_variance, found them through the archive index and extracted mean.o and variance.o. It never extracted max.o:
nm stats_static | grep stats_0000000000001240 T stats_mean
0000000000001290 T stats_varianceNo stats_max. This is why a static library should be many small objects: the unit of inclusion is the archive member, not the function. A library built as one giant object file would drag all of its code into every program that used any of it. Compiling with -ffunction-sections and linking the final program with -Wl,--gc-sections lets the linker drop unused functions inside a member as well.
The details of the archive tool, including replacing and deleting members, are in creating a static library with ar and linking against it.
Argument order and why linking fails
The linker reads its command line from left to right and keeps a running list of undefined symbols. When it meets an archive it extracts only the members that define a currently undefined symbol, then moves on and does not come back. So the position of a library on the command line matters:
gcc -L. -lstats main.c -o broken/usr/bin/ld: /tmp/cc4Hq1Zk.o: in function `main':
main.c:(.text+0x2c): undefined reference to `stats_mean'
/usr/bin/ld: main.c:(.text+0x3b): undefined reference to `stats_variance'
collect2: error: ld returned 1 exit statusWhen -lstats was processed there were no undefined symbols, so nothing was extracted. The cure is the rule every C programmer learns once: objects first, libraries after, and if library A uses library B, then A before B. The temporary file name in the message varies from run to run.
Circular dependencies between two archives need either a repeat of a library on the line or a group:
gcc main.o -Wl,--start-group -lalpha -lbeta -Wl,--end-group -o appInside the group the linker rescans the archives until no new symbols resolve. Use it as a last resort and fix the design if you can, since a cycle between libraries usually means they are one library.
Shared libraries do not suffer from this order sensitivity in the same way, since a shared library is considered as a whole when it is named, but on many distributions --as-needed is the default and makes the same ordering rule apply: a shared library listed before the objects that use it can be dropped from the dependency list as unneeded. The symptom is an undefined reference that looks identical, so the rule is the same.
Shared libraries: code loaded at run time
A shared library is an ELF file of type ET_DYN that the dynamic loader maps into a process when the program starts. The program's executable does not contain the library's code. It contains a note saying "I need libstats.so.1", and the loader finds the file and maps it. Several processes that use the same library share the same physical pages of its code, because the pages are read-only and identical.
Building one differs from building a static library in two ways. The code must be position independent, because the library can be loaded at a different address in every process, and the output is produced by the linker with -shared. Position independent code is requested with -fPIC at compile time:
gcc -O2 -Wall -fPIC -c mean.c variance.c max.c
gcc -shared -o libstats.so.1.0.0 -Wl,-soname,libstats.so.1 mean.o variance.o max.o
ln -s libstats.so.1.0.0 libstats.so.1
ln -s libstats.so.1 libstats.so
ls -l libstats*lrwxrwxrwx 1 dev dev 14 Nov 23 11:02 libstats.so -> libstats.so.1
lrwxrwxrwx 1 dev dev 18 Nov 23 11:02 libstats.so.1 -> libstats.so.1.0.0
-rwxr-xr-x 1 dev dev 15432 Nov 23 11:02 libstats.so.1.0.0Three names for one file, which the section on versioning explains. The compile flag -fPIC changes how the compiler accesses global data and calls functions: instead of absolute addresses, it uses offsets from the program counter and indirection through a table, so the code works wherever it lands. Compile without it and the link fails:
/usr/bin/ld: mean.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: failed to set dynamic section sizes: bad value
collect2: error: ld returned 1 exit statusThe message is exact and helpful. An object compiled for a fixed address contains absolute relocations a shared object cannot satisfy. A fuller look at the flags is in building a shared library with -shared and -fPIC. Link a program against the new library:
gcc -O2 main.c -L. -lstats -o stats_shared
./stats_shared./stats_shared: error while loading shared libraries: libstats.so.1: cannot open shared object file: No such file or directoryThe link succeeded and the run failed. The linker found libstats.so in -L. at build time and recorded the library's soname, libstats.so.1, in the program. At run time the loader searched its standard places, which do not include the current directory, and found nothing. This is the most common shared library error, and it is about the loader, not your code.
How the loader finds libraries
When a program starts, the dynamic loader reads its NEEDED entries and resolves each name by searching in a fixed order. In practice, for a modern binary, the order is: the directories in the program's RPATH if there is no RUNPATH, then the colon-separated LD_LIBRARY_PATH environment variable, then the program's RUNPATH, then the cache file /etc/ld.so.cache built by ldconfig, and finally the default directories /lib and /usr/lib. The mechanics are documented in the loader's manual page. You have four ways to make the example run, and each fits a different situation.
For a quick test, set the environment variable for one run:
LD_LIBRARY_PATH=. ./stats_sharedmean=5.00 variance=4.00For something that has to work without the user's environment, embed a runpath at link time. The token $ORIGIN expands to the directory of the executable, so the library can live beside it:
gcc -O2 main.c -L. -lstats -Wl,-rpath,'$ORIGIN' -o stats_shared
./stats_sharedmean=5.00 variance=4.00Quote $ORIGIN so the shell does not expand it. For a system-wide install, copy the library to a directory the loader knows, such as /usr/local/lib, and run ldconfig to refresh the cache. And for a directory outside the standard set, list it in a file under /etc/ld.so.conf.d/ before running ldconfig. A full discussion of the search order and its traps is in how ld.so finds libraries, and a worked example of shipping an application with its own libraries is in shipping a relocatable Linux app bundle.
Check what a program will look for, and what it resolves to, without guessing:
readelf -d stats_shared | grep -E 'NEEDED|RUNPATH'
ldd stats_shared 0x0000000000000001 (NEEDED) Shared library: [libstats.so.1]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN]
linux-vdso.so.1 (0x00007ffc4a5f2000)
libstats.so.1 => /home/dev/lib/./libstats.so.1 (0x00007f1c5e3a0000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1c5e000000)
/lib64/ld-linux-x86-64.so.2 (0x00007f1c5e3c0000)readelf shows the intent, ldd shows the outcome. When they disagree, the cause is the search order. A line ending in not found in the ldd output names the missing library. Use readelf -d instead of ldd for a binary you do not trust, since ldd can run code from it.
Link time and run time are different moments
The clearest way to hold the two kinds in your head is to separate when each is used. A static library is consumed once, at link time, and then it is gone: the program carries its own copy. A shared library is consumed twice. At link time the linker reads it to check that the symbols exist and records the soname. At run time the loader finds the file again and maps it. The two moments can see different files, and that gap is where most shared library bugs live. You may link against version 1.4 of a library and run against 1.2, which lacks a function the program needs. The loader will report it as symbol lookup error, or, with lazy binding, wait until the first call:
./stats_shared: symbol lookup error: ./stats_shared: undefined symbol: stats_medianTwo mitigations exist. Pass -Wl,-z,now when linking, which resolves all symbols at startup and fails fast, before the program has done any work. And use symbol versioning or a minimum version check so that a program built against a newer library refuses to start on an older one, instead of failing in the middle of a run.
Position independent code, and what it costs
-fPIC is not free, but its cost is smaller than people expect. On x86-64 the compiler can address global variables relative to the instruction pointer, so most data accesses cost the same as before. The extra cost appears in two places. Calls to functions that can be interposed, meaning any global function a user might replace, go through a table, the procedure linkage table, instead of a direct jump. And accesses to global variables defined in another shared object go through the global offset table, one extra load. Compiling a library with -fvisibility=hidden and exporting only the public API removes the first cost for internal calls, because a hidden symbol can never be replaced and the compiler calls it directly.
On 32-bit x86 the cost is higher, because the architecture lacks instruction-pointer-relative addressing and PIC code reserves a register. On Arm and RISC-V it is small. If you build a static library that may be linked into a shared object later, compile it with -fPIC too, or the link of that shared object fails with the relocation error shown above.
Static or shared: a decision table
Neither kind is better. They trade different things, and the table lists the trade by property:
| Property | Static library | Shared library |
|---|---|---|
| Executable size | larger, contains the code | smaller, contains a reference |
| Files to deploy | one | the program and each library |
| Startup time | fastest, nothing to load | slower, loader maps and relocates |
| Memory with many processes | each has its own copy | one copy of code pages is shared |
| Fixing a bug in the library | rebuild and redistribute every program | replace one file |
| Version mismatch at run time | impossible | possible, causes symbol lookup error |
| Security fixes | each program must be rebuilt | one update fixes all programs |
Plugins loaded by dlopen | not possible | the only way |
Code interposition (LD_PRELOAD) | not possible | possible |
| License effects (LGPL) | stricter, you must allow relinking | looser, the user can swap the library |
We think the right default for application code on a general-purpose Linux system is to link against shared libraries that the distribution provides, and to link your own small helper code statically. The system libraries receive security fixes without your involvement, and your helpers are yours to control. The exceptions are real. A single self-contained binary for a container or a rescue image favors static linking. A tool shipped to machines you do not manage favors a bundle or static linking, because you cannot count on the right library being there. A library used by dozens of programs in one system, such as a codec, favors a shared build, because one update fixes them all.
Be careful with fully static linking against glibc. The C library uses dlopen internally for name service lookups and locale data, so a program linked with -static that calls getaddrinfo or getpwnam can fail or pull in a different library at run time, and the linker warns about it. Statically linking against musl avoids this, at the cost of other differences. A common compromise is to link everything static except the C library, with -static-libgcc and the specific archives named on the command line.
Names and versions: soname, real name, linker name
The three files we created in the shared build are a convention, and the loader depends on it. The real name, libstats.so.1.0.0, is the file that holds the code. The soname, libstats.so.1, is the name the library announces for itself and the name programs record. The linker name, libstats.so, is a symlink the linker follows when you write -lstats. The soname is the compatibility promise: any file with that soname must offer the same interface to programs built against it.
That arrangement lets you upgrade without rebuilding. Ship libstats.so.1.0.1 with a bug fix, repoint the libstats.so.1 link, and every program that asked for libstats.so.1 runs the new code on its next start. Make an incompatible change, such as removing a function or changing a signature, and you build libstats.so.2 with the soname libstats.so.2. Old programs keep asking for version 1, and both can be installed together. The step-by-step version of that story is in versioning a shared library with -Wl,-soname, and the three names are explained in shared library sonames, real names and linker names.
The mistake that bites is building without -Wl,-soname. The library then has no soname and programs record whatever name the linker used to find it, usually the unversioned linker name. The loader will then accept any libstats.so on the search path, including one with an incompatible interface. Always set a soname, and verify it:
readelf -d libstats.so.1.0.0 | grep SONAME 0x000000000000000e (SONAME) Library soname: [libstats.so.1]Decide the rules for a major bump before you need them. Bump it when you remove or change a public function, change the layout of a public structure, change a constant's value or change what a return value means. Do not bump it for a new function or an internal fix. Designing a stable C ABI for a shared library lists the habits that keep a bump rare, such as opaque handles and size-tagged structures.
Controlling what a shared library exports
By default, every global function and variable in a shared library is exported, which means it is visible to every program that links against it and to every other library in the process. That is a large public surface, and it has three costs. Internal helpers become part of the ABI because someone, somewhere, will call them. Two libraries that both define a helper with the same name can silently replace each other's version at run time, a failure called symbol interposition. And calls inside the library to its own exported functions go through the procedure linkage table, so they cannot be inlined.
The remedy is to hide everything and export on purpose. Compile with -fvisibility=hidden and mark the public functions:
#ifndef STATS_EXPORT_H
#define STATS_EXPORT_H
#define STATS_API __attribute__((visibility("default")))
#endif#include "stats.h"
#include "stats_export.h"
STATS_API double stats_mean(const double *v, size_t n)
{
double sum = 0;
for (size_t i = 0; i < n; i++) {
sum += v[i];
}
return n ? sum / (double)n : 0.0;
}gcc -O2 -fPIC -fvisibility=hidden -c mean.c variance.c max.c
gcc -shared -o libstats.so.1.0.0 -Wl,-soname,libstats.so.1 mean.o variance.o max.o
nm -D --defined-only libstats.so.1.0.00000000000001110 T stats_meanOnly stats_mean appears in the dynamic symbol table, because only it carries the default visibility attribute. The other two sources were not marked, so they are hidden, and stats_variance, which calls stats_mean, now calls it directly. If you do want all three exported, mark each, and let the exported list be the same as the header. The list printed by nm -D --defined-only is the ABI, so compare it with the header in every release, and check it in CI. The full treatment of the options, including version scripts that export a precise list, is in controlling symbol visibility with -fvisibility=hidden.
Interposition, preloading and why it works
Because the dynamic loader resolves symbols by name across all loaded objects in order, a definition earlier in the search order wins. That is how LD_PRELOAD works: a library listed there is searched first, so a function it defines replaces the same-named function in every later library, including the C library. It is a useful tool, since it lets you wrap malloc for tracing or substitute a test double, and it is the reason a shared library's exported functions are not called directly inside the library unless they are hidden or the library is linked with -Bsymbolic.
A minimal wrapper shows the mechanism:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stddef.h>
double stats_mean(const double *v, size_t n)
{
double (*real)(const double *, size_t) =
(double (*)(const double *, size_t))dlsym(RTLD_NEXT, "stats_mean");
fprintf(stderr, "stats_mean called with n=%zu\n", n);
return real(v, n);
}gcc -O2 -fPIC -shared -o libtrace.so trace.c -ldl
LD_PRELOAD=./libtrace.so LD_LIBRARY_PATH=. ./stats_sharedstats_mean called with n=8
stats_mean called with n=8
mean=5.00 variance=4.00The wrapper printed twice. The first call comes from main, and the second from stats_variance inside the library, which calls stats_mean by name and so reaches the interposed version. Hide stats_mean with the visibility attribute and the second call goes straight to the real function, and the wrapper sees only one. Neither result is a bug. They show why visibility is a design decision and not a cosmetic one. Static libraries have no equivalent, since there is no loader step, which is why preloading a wrapper over a statically linked program does nothing.
Loading libraries by hand with dlopen
The linker and loader handle libraries named at build time. A plugin system needs the opposite: load a library chosen at run time. The functions dlopen, dlsym and dlclose, declared in <dlfcn.h>, do it. Link the host with -ldl on older glibc versions, which became part of libc in glibc 2.34:
#include <dlfcn.h>
#include <stdio.h>
int main(int argc, char **argv)
{
void *lib = dlopen(argc > 1 ? argv[1] : "./libstats.so", RTLD_NOW);
if (!lib) {
fprintf(stderr, "dlopen: %s\n", dlerror());
return 1;
}
double (*mean)(const double *, size_t) =
(double (*)(const double *, size_t))dlsym(lib, "stats_mean");
if (!mean) {
fprintf(stderr, "dlsym: %s\n", dlerror());
return 1;
}
double v[] = {1, 2, 3};
printf("mean=%.1f\n", mean(v, 3));
dlclose(lib);
return 0;
}gcc -O2 host.c -o host
./host ./libstats.so
./host ./missing.somean=2.0
dlopen: ./missing.so: cannot open shared object file: No such file or directoryRTLD_NOW resolves every symbol at load time, so a missing dependency fails immediately with a message from dlerror. RTLD_LAZY defers function resolution to first use. The program has no link-time reference to the library at all, so nothing is recorded in its NEEDED list. Only a shared library can do this. A deeper look at the flags and at loading from memory is in the dynamic loading topic of this site.
Finding out what the loader is doing
When a library is not found or the wrong one is picked up, ask the loader to narrate. The environment variable LD_DEBUG takes a list of categories, and libs shows the search:
LD_DEBUG=libs ./stats_shared 2>&1 | head -12 12345: find library=libstats.so.1 [0]; searching
12345: search path=/home/dev/lib/tls/haswell/x86_64:/home/dev/lib/tls/haswell:/home/dev/lib/tls/x86_64:/home/dev/lib/tls:/home/dev/lib/haswell/x86_64:/home/dev/lib/haswell:/home/dev/lib/x86_64:/home/dev/lib (RUNPATH from file ./stats_shared)
12345: trying file=/home/dev/lib/tls/haswell/x86_64/libstats.so.1
12345: trying file=/home/dev/lib/libstats.so.1
12345: find library=libc.so.6 [0]; searching
12345: search path=/home/dev/lib (RUNPATH from file ./stats_shared)Each trying file= line is a path the loader tested, and the note after the search path says which mechanism supplied it. The process number and the directory names are an example. Use LD_DEBUG=bindings to see which library satisfied each symbol, which is the way to catch an unexpected interposer, and LD_DEBUG=help to list the categories.
How the linker picks between libstats.so and libstats.a
When both kinds sit in the same directory and you write -lstats, the linker picks the shared one. Its search is, for each directory in the path, to try libstats.so first and libstats.a second, and to stop at the first match. That default surprises people who built both and expected the static one to be used. Four ways exist to choose explicitly:
| Goal | How |
|---|---|
| Force the static archive for one library | name the file: gcc main.c ./libstats.a |
| Force static for one library among shared ones | -Wl,-Bstatic -lstats -Wl,-Bdynamic |
| Make the whole program static | gcc -static main.c -L. -lstats |
| Prefer shared, allow fallback | the default behavior of -lstats |
The -Bstatic and -Bdynamic pair is a toggle, and it applies to every -l between them, so always switch back with -Bdynamic before the C library appears on the line. Forgetting the switch back makes the linker look for a static libc.a, which may not be installed, and produces cannot find -lc. The line to remember is that the toggles are positional, exactly like the library order itself.
Verify what you got instead of trusting what you typed. A statically linked library leaves no NEEDED entry, and a shared one leaves exactly one:
gcc main.c -L. -Wl,-Bstatic -lstats -Wl,-Bdynamic -o mixed
readelf -d mixed | grep NEEDED 0x0000000000000001 (NEEDED) Shared library: [libc.so.6]Only the C library appears. The statistics code is inside the executable, and the libstats name is not recorded. This mixed form is the most common practical choice: your own helpers are static, the system libraries are shared, and the result needs nothing from the build directory at run time.
As-needed linking and the silent dropped library
Many distributions pass --as-needed to the linker by default. With it, the linker records a NEEDED entry for a shared library only if some object before it on the command line actually uses a symbol from it. That keeps dependency lists short and makes upgrades less risky, and it produces a classic confusing failure when a library is placed too early:
gcc -Wl,--as-needed -lm main.c -o app/usr/bin/ld: /tmp/ccMk3o9d.o: in function `main':
main.c:(.text+0x17): undefined reference to `sqrt'
collect2: error: ld returned 1 exit statusThe math library was named first, nothing needed it yet, so the linker dropped it, and then the call to sqrt had no definition. The error looks identical to the archive ordering error, and the cure is the same: put the library after the code that uses it. If a program depends on a library only for its side effects, such as a plugin that registers itself in a constructor, --as-needed removes it and the side effect never happens. Wrap that library in -Wl,--no-as-needed when you must keep it:
gcc main.c -Wl,--no-as-needed -lplugin_registry -Wl,--as-needed -o appThe inverse test is worth running on your own builds. After linking, list the NEEDED entries and ask if each is justified. A library that appears there with no symbol used from it makes your program fail to start on a machine without it, for no benefit. Build with -Wl,--as-needed and compare the lists to see which entries it removes.
Libraries and link-time optimization
Link-time optimization lets the compiler see across files at link time, inline across translation units and remove dead code. It interacts with libraries in a way that decides which kind is faster for some programs. A static library built with -flto stores its objects in an intermediate form, and when the program links, the compiler optimizes your code and the library's together. A call to stats_mean from main can be inlined into the caller, and the loop in it can be vectorized with knowledge of the caller's constants. A shared library is a closed box at link time: its code is already compiled and the call goes through the procedure linkage table, so none of that can happen.
Using it takes two steps. Compile the library sources with -flto and create the archive with the LTO-aware tools:
gcc -O2 -flto -c mean.c variance.c max.c
gcc-ar rcs libstats_lto.a mean.o variance.o max.o
gcc -O2 -flto main.c libstats_lto.a -o stats_ltogcc-ar is a wrapper that loads the plugin the archiver needs to read the intermediate objects. With the plain ar the archive can lack a usable symbol index and the link fails with plugin needed to handle lto object. The result of the build is a program in which stats_mean may no longer exist as a separate function, because it was inlined. Do not infer a speedup from that: whether it helps is a measurement on your program, with your compiler version, and we make no claim without one.
The tradeoff is that an LTO static library ties its users to a compatible compiler. Distribute it only if you also pin the compiler version, or ship a non-LTO build for general use.
Upgrading a library under a running program
A last point separates the two kinds in operation. Replace a shared library file while a program is running and what happens depends on how you replace it. Overwriting the file in place with cp truncates the inode the process has mapped, and the process can crash with a bus error when it touches a page that no longer exists. Installing a new file under a temporary name and moving it over the old one with mv, which is an atomic rename, leaves the old inode alive for the running process and gives new processes the new file. That is what package managers do, and it is why install and package tools write to a temporary path first.
Test it yourself on a throwaway copy. Start a long-running program that uses the library, replace the file with mv, check that the running program keeps its old copy and a new run gets the new one:
./stats_shared_long &
cp libstats.so.1.0.0 libstats.so.1.0.0.new
mv libstats.so.1.0.0.new libstats.so.1.0.0
lsof -p $! | grep libstatsstats_shared_long 4121 dev mem REG 8,1 15432 1310731 /home/dev/lib/libstats.so.1.0.0 (deleted)The word (deleted) shows that the running process still holds the old inode, whose name is gone from the directory. The new file is at the same path for the next process. The inode number and size are an example. A static program has no such concern, since its code is inside its own file, but it also never picks up the fix, which is the other side of the same tradeoff.
One Makefile that builds both
A library project should produce both kinds from one set of rules, so users can pick. The only difference between the builds is the compile flag and the final command. Keep two object directories, since the same source compiled with and without -fPIC gives different objects, and mixing them is a classic cause of the relocation error from earlier:
CC ?= gcc
CFLAGS ?= -O2 -Wall -Wextra
SRC := mean.c variance.c max.c
MAJOR := 1
VERSION := 1.0.0
PREFIX ?= /usr/local
OBJ_STATIC := $(SRC:%.c=build/static/%.o)
OBJ_SHARED := $(SRC:%.c=build/shared/%.o)
all: build/libstats.a build/libstats.so.$(VERSION)
build/static/%.o: %.c stats.h
@mkdir -p $(@D)
$(CC) $(CFLAGS) -c $< -o $@
build/shared/%.o: %.c stats.h
@mkdir -p $(@D)
$(CC) $(CFLAGS) -fPIC -fvisibility=hidden -c $< -o $@
build/libstats.a: $(OBJ_STATIC)
ar rcs $@ $^
build/libstats.so.$(VERSION): $(OBJ_SHARED)
$(CC) -shared -o $@ -Wl,-soname,libstats.so.$(MAJOR) $^
ln -sf libstats.so.$(VERSION) build/libstats.so.$(MAJOR)
ln -sf libstats.so.$(MAJOR) build/libstats.so
clean:
rm -rf buildThe two pattern rules keep the object sets apart. The static archive is built from plain objects and the shared library from position independent ones with hidden visibility. The soname is derived from MAJOR, so there is one variable to change for an incompatible release. A build with make leaves everything in build/, and the tree is clean to remove.
The same project in CMake is shorter, because the generator knows the conventions:
cmake_minimum_required(VERSION 3.20)
project(stats VERSION 1.0.0 LANGUAGES C)
add_library(stats_obj OBJECT mean.c variance.c max.c)
set_target_properties(stats_obj PROPERTIES POSITION_INDEPENDENT_CODE ON
C_VISIBILITY_PRESET hidden)
add_library(stats_static STATIC $<TARGET_OBJECTS:stats_obj>)
set_target_properties(stats_static PROPERTIES OUTPUT_NAME stats)
add_library(stats_shared SHARED $<TARGET_OBJECTS:stats_obj>)
set_target_properties(stats_shared PROPERTIES OUTPUT_NAME stats
VERSION ${PROJECT_VERSION}
SOVERSION 1)SOVERSION produces the soname, and VERSION the real name, with the symlinks created by CMake. Sharing one object library for both kinds, as here, is simple and means the static archive is also position independent, which costs a little speed on 32-bit targets and nothing noticeable on x86-64. If that matters, build two object sets as in the Makefile.
Installing and describing the library
A library without its headers and a description is hard to use. Install four things: the shared library with its links, the static archive, the header, and a pkg-config file. The install rule, honoring DESTDIR for packagers, completes the Makefile:
install: all
install -d $(DESTDIR)$(PREFIX)/lib $(DESTDIR)$(PREFIX)/include $(DESTDIR)$(PREFIX)/lib/pkgconfig
install -m 755 build/libstats.so.$(VERSION) $(DESTDIR)$(PREFIX)/lib/
ln -sf libstats.so.$(VERSION) $(DESTDIR)$(PREFIX)/lib/libstats.so.$(MAJOR)
ln -sf libstats.so.$(MAJOR) $(DESTDIR)$(PREFIX)/lib/libstats.so
install -m 644 build/libstats.a $(DESTDIR)$(PREFIX)/lib/
install -m 644 stats.h $(DESTDIR)$(PREFIX)/include/
install -m 644 stats.pc $(DESTDIR)$(PREFIX)/lib/pkgconfig/prefix=/usr/local
libdir=${prefix}/lib
includedir=${prefix}/include
Name: stats
Description: Small statistics helpers
Version: 1.0.0
Libs: -L${libdir} -lstats
Libs.private: -lm
Cflags: -I${includedir}After installing to a system path, run ldconfig so the loader cache sees the new soname. Users then compile with gcc app.c $(pkg-config --cflags --libs stats), and a request for --static adds the private libraries. The fields and traps of the .pc file are the subject of shipping a library with a pkg-config .pc file.
A final check belongs in your release process. Install into a staging directory with make install DESTDIR=/tmp/stage, then verify the pieces: the symlink chain with ls -l, the exported symbols with nm -D --defined-only, the soname with readelf -d, and a test program that links through pkg-config and runs with a clean environment. If all five agree, a user on a clean machine will not meet a surprise.
Tests that catch library bugs
Libraries need two kinds of tests that application code can skip. The first checks the exported interface. Keep a file with the exact list of public symbols and compare it with the build's output on every change:
nm -D --defined-only build/libstats.so.1.0.0 | awk '{print $3}' | sort > symbols.actual
diff symbols.expected symbols.actual && echo "interface unchanged"interface unchangedA symbol that appears is a new promise and one that disappears is a break, and both should be deliberate. The second kind runs the test suite against the installed library, through the soname, from a directory that does not contain the build tree. A test that links against build/libstats.a and passes tells you nothing about what a user will get from the shared build, because the code paths differ: visibility, interposition, -fPIC, and relocation processing exist only in the shared case. Run each test twice, once linked static and once shared, and treat a difference as a bug.
Add the sanitizers for development builds: -fsanitize=address,undefined on the test program and the library. They work with shared libraries, and preload ordering matters, so link the program with the sanitizer runtime first, which gcc does by default when the flag is on the link line.
Pitfalls, collected
Most trouble with libraries repeats. These are the ones we see most, each with its cause:
| Symptom | Cause | Fix |
|---|---|---|
undefined reference to a function in your library | library listed before the objects that use it | put libraries after objects |
cannot find -lstats | no libstats.so or .a in the search path | add -L, create the linker-name symlink |
cannot open shared object file at run time | loader cannot find the soname | ldconfig, RUNPATH or LD_LIBRARY_PATH |
recompile with -fPIC | objects in a shared library built without it | compile every object with -fPIC |
symbol lookup error | run-time library older than the one linked against | match versions, link with -z now, use versioned symbols |
multiple definition of | the same function in an object and an archive, or two objects | remove one definition, check what nm -A shows |
| program uses the wrong library copy | an LD_LIBRARY_PATH or RPATH directory is searched first | inspect with LD_DEBUG=libs |
| crash after upgrading a library | ABI change without a new soname | bump the major, check with an ABI diff tool |
static link warns about getaddrinfo | glibc uses dlopen internally | link dynamically against glibc or use musl |
When none of these match, go to the tools in order: readelf -d on the program for NEEDED and paths, ldd for what resolved, nm -D on the library for what it exports, and LD_DEBUG=libs,bindings for what the loader did. Each answers one question and between them they explain nearly every failure.
Where this guide stops
This guide covered libraries on Linux with GNU tools, which is the usual platform for learning. Other systems differ in names and mechanics, not in the ideas. Windows uses DLLs with import libraries and an explicit export list, macOS uses .dylib files with install names that play the role of the soname, and embedded systems usually have only static libraries because there is no loader. Three subjects deserve their own reading. GNU symbol versioning lets one shared library carry several versions of a function and is how glibc keeps decades of programs working. The -Bsymbolic and -z linker options control interposition and hardening. And link-time optimization crosses the library boundary for static libraries and not for shared ones, which can change which kind is faster.
If you remember one thing, make it the split between the two moments. At link time, the linker reads your library and decides what to copy or record. At run time, the loader reads your program and finds what it recorded. Nearly every bug in this area is a disagreement between the two moments, and nearly every fix is to make them agree: the same library version, the same search path, the same soname, the same compile flags.


