Go cgo "undefined reference" (C link) - Fix in CI
cgo compiles fine but the linker still needs the actual C library to resolve symbols. When the -dev package is absent or no -l flag names it, the link step fails with "undefined reference".
What this error means
A cgo build fails at link time with undefined reference to "X". The header was found at compile time but the library to satisfy the symbol was never installed or never linked.
/usr/bin/ld: $WORK/b001/_cgo_main.o: in function "main":
undefined reference to "git_libgit2_init"
collect2: error: ld returned 1 exit statusCommon causes
Library -dev package not installed
The runner has headers but not the actual .so/.a, so the linker has no symbols to bind against.
Missing -l link flag
The cgo LDFLAGS directive does not name the library, so the linker never pulls it in.
How to fix it
Install the C library and link it
- Install the -dev package providing the headers and the link target.
- Name the library in a cgo LDFLAGS directive.
// #cgo LDFLAGS: -lgit2
import "C"Add an install step in CI
- Install the system library before building so the linker can find it.
- run: sudo apt-get update && sudo apt-get install -y libgit2-devHow to prevent it
- Install C -dev packages in CI before any cgo build.
- List every needed library in cgo LDFLAGS.
- Prefer pkg-config in the cgo directive so flags track the installed version.