Free — no signup required

The Hidden Costs of CGO

2 min read

It Is Not Just "Go with C"

Adding CGO to your project is not a free lunch. It fundamentally changes your build and runtime characteristics in ways that surprise engineers who have not worked with it before.

Build complexity: You can no longer run go build on any machine. You need a C compiler (gcc or clang) installed. Cross-compilation — building a Linux binary from a Mac, for example — becomes significantly harder because you need a C cross-compiler targeting the right architecture and OS. This breaks the "compile anywhere" simplicity that makes Go attractive for DevOps tooling. Docker-based build pipelines often need to install gcc explicitly, adding image size and build time.

Performance overhead per call: Calling a C function is not free. Go goroutines use small, dynamically growing stacks (starting at 2KB). C functions use standard OS thread stacks (typically 8MB). Every CGO call requires the runtime to: pause the goroutine scheduler, switch to an OS thread stack, save CPU registers, execute the C function, restore registers, and switch back. This overhead is roughly 50–200 nanoseconds per call. Calling a C function in a tight loop (millions of times per second) can make CGO slower than a pure-Go equivalent, even if the C function itself is faster.

No panic recovery: If the C code crashes with a segmentation fault, your entire Go program crashes. Go's recover() mechanism only catches Go panics — it cannot intercept signals raised by C code. This means a bug in a C dependency can take down your entire service, not just one request.

Practical guidance: Batch your CGO calls. If you must call a C function many times, do it in large chunks from Go rather than calling it once per item. Many CGO-based libraries (like mattn/go-sqlite3) are designed around this principle — they batch operations into transactions to amortize the per-call overhead.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free