Go "-race requires cgo" in CI - Fix the test run
The race detector is implemented with cgo, so it needs CGO_ENABLED=1 and a working C compiler. A CGO-disabled or compiler-less environment cannot run -race.
What this error means
A run fails with -race requires cgo; enable cgo by setting CGO_ENABLED=1 or a C-compiler-not-found error under -race. It means CGO is off or no gcc is installed.
go test: -race requires cgo; enable cgo by setting CGO_ENABLED=1Common causes
CGO_ENABLED=0 in the environment
CGO is disabled globally, but -race needs it on, so the race build cannot proceed.
No C compiler for the race runtime
CGO is on but the runner has no gcc/clang to compile the race detector runtime.
How to fix it
Enable cgo and install a compiler
- Set CGO_ENABLED=1 and ensure gcc is installed before running -race.
- run: sudo apt-get update && sudo apt-get install -y build-essential
- run: CGO_ENABLED=1 go test -race ./...Keep -race jobs on a toolchain-equipped image
- Run race tests on a runner image that ships a C toolchain.
CGO_ENABLED=1 go test -race ./...How to prevent it
- Set
CGO_ENABLED=1for race-test jobs. - Install a C toolchain on runners that run
-race. - Separate pure-Go build jobs from race-test jobs if needed.