cgo: C from Go and the cost of it
cgo lets a Go program call C: a comment above import "C" holds the C declarations, and the toolchain runs a C compiler on the generated glue. It is how Go talks to a system library that has no Go equivalent, and it is the one feature that turns a simple static build into a platform-specific one. The previous lesson showed the cost in cross builds; this one shows the call.
A preamble and a call
The preamble declares two static functions so the example needs no external library; a real program includes the header it needs and links the library with a #cgo LDFLAGS line. A Go string is not a C string, so C.CString copies it into C memory, and C.free in a defer returns it: the C allocator does not know about the Go collector, and forgetting the free leaks on every call.
package main
/*
#include <stdlib.h>
#include <string.h>
static int c_len(const char *s) {
return (int)strlen(s);
}
static int add(int a, int b) {
return a + b;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
s := "héllo"
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
fmt.Println("C strlen:", C.c_len(cs), "Go len:", len(s))
fmt.Println("C add:", C.add(2, 3))
}
go build -o app-cgo .
./app-cgo
C strlen: 6 Go len: 6
C add: 5
file -b app-cgo | cut -d, -f1-4
ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked
go env CGO_ENABLED CC
1
cc
The C function read the UTF-8 bytes and reported six, while the Go length is also six: a Go string is bytes and C reads bytes, so this pair agrees. The file line shows a dynamically linked executable, which is the difference a C library makes, and the last line reports the enabled flag and the compiler the toolchain will use.
The same program without cgo
CGO_ENABLED=0 removes the C compiler from the build, and a package that imports "C" then fails: there is no way to compile the preamble without a C toolchain. That failure is the decision point of every project that considers cgo, because it is also the flag that makes cross compilation and small static containers possible.
package main
/*
#include <stdlib.h>
#include <string.h>
static int c_len(const char *s) {
return (int)strlen(s);
}
static int add(int a, int b) {
return a + b;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
s := "héllo"
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
fmt.Println("C strlen:", C.c_len(cs), "Go len:", len(s))
fmt.Println("C add:", C.add(2, 3))
}
CGO_ENABLED=0 go build -o app-nocgo .
package example.com/cgo: build constraints exclude all Go files in /tmp/gengo3/run/056/nocgo
The message names the package and the reason. A pure-Go alternative exists for most of the usual cases: net and os/user have pure-Go builds, SQLite has pure-Go ports, and a small C library can often be replaced by a few hundred lines of Go. When it cannot, the project accepts the constraint and builds the cgo target on a matching machine.
What a cgo call costs
A call from Go into C crosses the scheduler boundary: it costs more than a Go call, it cannot be inlined, and a long C call blocks the goroutine unless the runtime can hand the thread off. The pointer rules are strict: Go memory passed to C must not contain Go pointers, and the C code must not keep a Go pointer after the call returns. Those rules are why the conversions copy, and why a hot loop over cgo calls is usually the wrong design.
Exercises
- Call C.strlen on a string with a non-ASCII character and compare the result with len. Why do they agree here and where would they not?
- Add a function that returns a C string, convert it with C.GoString and free it. Which side owns the memory at each step?
- Build the example with CGO_ENABLED=0 and then replace the C call with len. Which binary is smaller, and by how much?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the comment above import "C" contain?
Answer
C declarations and preprocessor lines
It is the preamble the C compiler sees.
-
Why does C.CString need C.free?
Answer
It allocates C memory that the Go collector does not manage
The C allocator owns that memory and only free returns it.
-
What does CGO_ENABLED=0 do to a package importing C?
Answer
The build fails, because there is no C compiler step
cgo cannot be emulated; the flag removes the toolchain.
-
Why does cgo make cross-compilation hard?
Answer
The C part needs a compiler for the target platform
A target C toolchain is a separate dependency.
-
Which strings can be passed to C as a pointer?
Answer
C memory made by C.CString or a C allocation
Go memory with pointers cannot cross the boundary; the conversions copy.
-
What does a cgo binary usually link against?
Answer
The system C library
That is why it is dynamic where a pure-Go build is static.
-
What does a cgo call cost compared with a Go call?
Answer
More, because it crosses the scheduler boundary
The call cannot be inlined and has runtime overhead.
-
What must not happen to a Go pointer passed to C?
Answer
It must not be stored by the C code after the call
The garbage collector may move the object once the call returns.
-
Which is a good reason to choose cgo?
Answer
A system library with no pure-Go equivalent
The cost is real, so the dependency has to be necessary.
-
What did C strlen and Go len agree on for héllo?
Answer
Six, because both count bytes
A Go string is bytes, and C reads the same bytes.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev