Skip to content
Latchkey

ld: Usage, Options & Common CI Errors

ld combines object files and libraries into a single executable or shared object.

ld is the final stage of a build. You rarely call it directly - the compiler driver does - but its two errors, "undefined reference" and "cannot find -lXXX", dominate C/C++ CI logs and both come down to libraries and link order.

What it does

ld is the GNU linker. It resolves symbols across object files and libraries, applies relocations, and produces an executable or shared library. The compiler driver (gcc/clang) normally invokes it with the right runtime objects, so prefer driving links through gcc rather than ld directly.

Common usage

Terminal
gcc main.o util.o -o app -lm           # let the driver call ld
ld -o app crt1.o main.o -lc            # direct (rarely needed)
gcc main.o -o app -L/opt/lib -lfoo     # add a search path
gcc main.o -o app -Wl,-rpath,/opt/lib  # embed a runtime path
gcc a.o b.o -o app -Wl,--start-group -lx -ly -Wl,--end-group

Options

FlagWhat it does
-o <file>Output file name
-l<name> / -L <dir>Link libname / add a search dir
-rpath <dir>Embed a runtime library search path
--start-group ... --end-groupResolve circular library deps
-sharedProduce a shared object (.so)
-staticLink statically

Common errors in CI

undefined reference to symbol - a library providing the symbol is missing or listed before the code that needs it; with static libs, link order matters (put -l after the objects, or wrap mutually dependent libs in -Wl,--start-group). "cannot find -lfoo" - the library file is not in any -L path; install the -dev package or add -L. "DSO missing from command line" means a transitively needed .so must be named explicitly. Errors are funneled through "collect2: error: ld returned 1 exit status".

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →