Go "-race requires cgo" - Fix Race Detector Setup in CI
Go’s race detector is built on a C runtime, so go test -race requires cgo enabled and a working C compiler. With CGO_ENABLED=0 or no gcc/clang on the runner, the race build cannot proceed.
What this error means
A go test -race ./... step fails immediately with -race requires cgo or go test: -race is only supported on <list> with cgo. Non-race tests run fine; only the race build fails.
go test: -race requires cgo
# or
-race is only supported on linux/amd64, ... and requires cgoCommon causes
CGO_ENABLED=0 disables the race runtime
A pipeline that sets CGO_ENABLED=0 (often for static builds) turns off cgo, but the race detector cannot be built without it.
No C compiler on a slim runner
The race detector needs gcc/clang. A minimal image without a C toolchain cannot build the instrumented binary.
How to fix it
Enable cgo for the race step
Turn cgo on so the race runtime can be compiled.
CGO_ENABLED=1 go test -race ./...Install a C compiler
# Debian/Ubuntu
apt-get update && apt-get install -y build-essential
# Alpine
apk add --no-cache build-base
CGO_ENABLED=1 go test -race ./...Run race tests on a supported platform
- Confirm the runner OS/arch is one the race detector supports (e.g. linux/amd64).
- Keep
CGO_ENABLEDunset or1for the race job specifically. - Bake the C toolchain into the runner image so the race build always works.
How to prevent it
- Run
-racejobs with cgo enabled and a C compiler present. - Do not set
CGO_ENABLED=0for the race-test step. - Bake
build-essential/build-baseinto images that run race tests.