Go Linker Errors - Fix "undefined reference" / ld Failures in CI
A cgo build compiled the C code but the external linker (ld) could not resolve a symbol or find a library. The fix is to install the missing system library or pass the right -l/-L flags.
What this error means
The build gets past compilation and fails at link time with undefined reference to <symbol>, cannot find -lfoo, or ld: library not found for -lfoo. The C code is fine; the linker just cannot find the library that provides the symbol.
# github.com/example/imaging
/usr/bin/ld: cannot find -ljpeg
collect2: error: ld returned 1 exit status
# or
undefined reference to `sqlite3_open_v2'Common causes
A required system library is not installed
cgo links against a shared/static library (libjpeg, libsqlite3, libssl) that the runner image does not have, so the linker cannot find it.
The linker has no path to the library
The library exists but is in a non-standard location, and no -L/CGO_LDFLAGS points the linker at it.
Missing -dev/-devel package for static linking
Linking needs the development package (headers and the .so/.a), not just the runtime library.
How to fix it
Install the missing library’s dev package
# Debian/Ubuntu - example for libjpeg
apt-get update && apt-get install -y libjpeg-dev
# RHEL/Fedora
dnf install -y libjpeg-turbo-develPoint cgo at the library location
When the library is in a custom path, pass the include and link flags to cgo.
export CGO_CFLAGS="-I/opt/lib/include"
export CGO_LDFLAGS="-L/opt/lib/lib -ljpeg"
go build ./...Identify the missing symbol or library
- Read whether it is
cannot find -lfoo(missing library) orundefined reference(missing symbol). - Map the
-lfooto its dev package and install it. - For
undefined reference, ensure the right library is on the link line viaCGO_LDFLAGS.
How to prevent it
- Bake the dev packages your cgo code links against into the runner image.
- Pin
CGO_CFLAGS/CGO_LDFLAGSfor non-standard library paths. - Prefer pure-Go dependencies to avoid the external linker entirely.