TExcelTAD
Home › Build Fundamentals: From Source to Binary › Field Notes: Linking & Libraries

Field Notes: Linking & Libraries

Practical lessons about object files and libraries that usually get learned the hard way, during a late-night release. Each one is short; several come with a session that shows the problem for real.

Read the first linker error, not the last

A failing link can print hundreds of lines. The last one, collect2: error: ld returned 1 exit status, carries no information. The first undefined reference is usually the cause, and the rest follow from it (one missing library leaves dozens of symbols undefined). Pipe a long log through grep -m1 'undefined reference' and fix that one first. For C++, the names are demangled by default; when you need the raw symbol to search with nm, link with -Wl,--no-demangle.

Make shared libraries fail at build time, not at load time

By default, a shared library may contain undefined symbols: the linker assumes some other library will provide them when the program runs. A typo in a library therefore surfaces only when an application loads it, possibly on a customer's machine. -Wl,--no-undefined (or -Wl,-z,defs) makes the library's own link fail instead:

bash · try it yourself
mkdir -p fn && cd fn
cat > lib.c <<'SRC'
void log_line(const char *msg);          /* declared, but defined nowhere */
int compute(int x) { log_line("compute"); return x * 2; }
SRC
gcc -fPIC -c lib.c
gcc -shared lib.o -o libcompute.so && echo "default: libcompute.so built (the bug is still inside)"
echo "--- with -Wl,--no-undefined"
gcc -shared lib.o -Wl,--no-undefined -o libcompute.so
default: libcompute.so built (the bug is still inside)
--- with -Wl,--no-undefined
/usr/bin/ld: lib.o: in function `compute':
lib.c:(.text+0x1a): undefined reference to `log_line'
collect2: error: ld returned 1 exit status

CMake, Meson and most distributions' packaging tools recommend this flag for libraries. The exception is plugins that intentionally use symbols from their host program.

Link only what you use: --as-needed

Every NEEDED entry costs load time, and a stale -lfoo left in a build script keeps a dependency alive long after the code stopped using it. With --as-needed, the linker records a shared library only if it actually resolves a symbol. Ubuntu and Debian's GCC turn it on by default, which this session undoes to show the difference:

bash · try it yourself
mkdir -p fn && cd fn
printf '#include <stdio.h>\nint main(void) { puts("no maths here"); return 0; }\n' > main.c
gcc main.c -lm -o default-link
gcc main.c -Wl,--no-as-needed -lm -o no-as-needed
for f in default-link no-as-needed; do printf '%-14s NEEDED: ' $f; readelf -d $f | grep -o 'Shared library: \[[^]]*\]' | sed 's/Shared library: //' | paste -sd' '; done
default-link   NEEDED: [libc.so.6]
no-as-needed   NEEDED: [libm.so.6] [libc.so.6]

The flip side: with --as-needed, order matters for shared libraries too (a library listed before the objects that use it is dropped), which is another reason to keep the "libraries after objects" rule from Link Errors & Link Order.

"Static" glibc is not fully static

-static makes a self-contained binary, except for glibc features that load plugins at run time: user and host lookups (getpwnam, getaddrinfo) go through NSS modules that are shared libraries. The linker warns, and the warning is serious:

bash · try it yourself
mkdir -p fn && cd fn
cat > who.c <<'SRC'
#include <pwd.h>
#include <stdio.h>
int main(void) {
    struct passwd *pw = getpwnam("root");
    printf("root's home: %s\n", pw ? pw->pw_dir : "?");
    return 0;
}
SRC
gcc -c who.c
gcc -static who.o -o who
./who
/usr/bin/ld: who.o: in function `main':
who.c:(.text+0x17): warning: Using 'getpwnam' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
root's home: /root

It works here because the build machine and the run machine are the same. Copied to a system with another glibc version, the lookup may fail or crash. For truly portable static binaries, use a C library designed for it (musl, as in Alpine Linux: musl-gcc or zig cc -target x86_64-linux-musl), or link dynamically and build on the oldest distribution you support, since glibc is backwards compatible but not forwards compatible.

Don't ship LD_LIBRARY_PATH

LD_LIBRARY_PATH in a launcher script works until two products' scripts set it differently, or it leaks into child processes that then load the wrong libraries. Use -Wl,-rpath,'$ORIGIN/../lib' for relocatable application bundles, install libraries in a directory the loader already searches for system packages, and keep LD_LIBRARY_PATH for debugging sessions.

Hide everything that isn't API

Build shared libraries with -fvisibility=hidden and mark the public API explicitly (Shared Libraries). Benefits: a smaller dynamic symbol table and faster loading, better optimisation (the compiler knows hidden functions can't be replaced at run time), no accidental clashes with other libraries' internals, and an export list you can review in a pull request.

Guard the ABI

Changing a struct's size, a function's parameters or an enum's values breaks programs that were compiled against the old headers, without any compile error. Before releasing a library:

  • compare the exported symbols of the old and new versions (nm -D --defined-only sorted, then diff);
  • for real ABI checks use libabigail's abidiff or the abi-compliance-checker;
  • bump the soname when the ABI breaks (Sonames, rpath & the Loader).

A crude but useful version of the first check:

bash · try it yourself
mkdir -p fn && cd fn
printf 'int api_open(void) { return 1; }\nint api_read(int n) { return n; }\nint api_close(void) { return 0; }\n' > v1.c
printf 'int api_open(void) { return 1; }\nint api_read(int n, int flags) { return n + flags; }\nint api_read_all(void) { return 0; }\n' > v2.c
gcc -fPIC -shared v1.c -o libapi.so.1
gcc -fPIC -shared v2.c -o libapi.so.2
diff <(nm -D --defined-only libapi.so.1 | awk '{print $3}' | sort) <(nm -D --defined-only libapi.so.2 | awk '{print $3}' | sort)
echo "diff exit status: $?"
1d0
< api_close
3a3
> api_read_all
diff exit status: 1

The diff catches the removed api_close and the added api_read_all. It cannot see that api_read gained a parameter: C symbols carry no types. That is exactly the kind of break abidiff (which reads debug info) exists for.

Test yourself

What does -Wl,--no-undefined do when building a shared library?

  1. Removes unused symbols
  2. Fails the link if the library has symbols that none of its inputs define
  3. Hides all symbols
  4. Makes the library static

Why is a -static binary using getpwnam not fully portable with glibc?

  1. It is too big
  2. glibc loads NSS modules (shared libraries) at run time for user lookups, which must match the glibc version used to link
  3. getpwnam is deprecated
  4. Static binaries can't print

Which ABI break did the nm-based diff miss?

  1. The removed api_close
  2. The added api_read_all
  3. api_read's new parameter
  4. None