Skip to content
Latchkey

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.

go
/usr/bin/ld: $WORK/b001/_cgo_main.o: in function "main":
undefined reference to "git_libgit2_init"
collect2: error: ld returned 1 exit status

Common 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

  1. Install the -dev package providing the headers and the link target.
  2. Name the library in a cgo LDFLAGS directive.
Go
// #cgo LDFLAGS: -lgit2
import "C"

Add an install step in CI

  1. Install the system library before building so the linker can find it.
.github/workflows/ci.yml
- run: sudo apt-get update && sudo apt-get install -y libgit2-dev

How 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.

Frequently asked questions

What causes ""undefined reference to""?
The runner has headers but not the actual .so/.a, so the linker has no symbols to bind against.
How do I fix "undefined reference to"?
Install the C library and link it

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card