Skip to content
tezvyn:
Menu

Cgo: The Bridge Between Go and C Code

Source: pkg.go.devMediumHow cards are made

Cgo is Go's bridge to the C world, letting you call C functions and use C types from your Go code. It's for leveraging existing C libraries or low-level OS APIs. The footgun: cgo calls have high overhead and break Go's simple cross-compilation.

Why it exists

Go is a modern language, but decades of powerful, optimized C libraries exist for everything from graphics to scientific computing. Cgo was created to avoid reinventing the wheel, providing a mechanism for Go programs to leverage this vast ecosystem of existing C code.

The mental model

Think of cgo as a translation layer or a bridge between two different worlds: the Go runtime and the C execution environment. Crossing this bridge isn't free. Each call pays a performance "toll" to switch between Go's goroutine scheduler and the system's thread model, and to translate data types between the two languages.

How it works

You enable cgo by importing a pseudo-package named "C". Immediately before this import, you write a multi-line comment that acts as a "preamble." This preamble contains standard C code, like #include directives for C headers. From your Go code, you can then access C functions, types, and variables using the C. prefix, for example C.puts() or C.size_t. You can also pass compiler and linker flags within the preamble using special #cgo directives, like "// #cgo CFLAGS: -g" or "// #cgo LDFLAGS: -lm".

When to use it

Use cgo when you absolutely need to interface with an existing C library that has no pure Go equivalent. This is common for database drivers (like SQLite), GUI toolkits, specialized hardware drivers, or when you need to call low-level operating system APIs not exposed by the Go standard library.

When not to use it

Avoid cgo if a pure Go alternative exists. The performance overhead of cgo calls can be substantial, making it a poor choice for performance-critical inner loops. Furthermore, cgo breaks Go's simple cross-compilation model. A pure Go program can be cross-compiled easily, but a cgo-enabled program requires a full C cross-compilation toolchain for the target, which is much more complex to set up. Passing pointers between Go and C is also complex due to Go's garbage collector.

One canonical example

A common use is calling a function from the standard C library. To print a string using C's puts function, you must first convert the Go string to a C-compatible string, as they are not the same. The code looks like this: // #include <stdio.h> import "C" import "unsafe"

func main() {

cString := C.CString("Hello from C!") defer C.free(unsafe.Pointer(cString))

C.puts(cString)
}

This shows importing "C", including the header, converting the string, calling the C function, and freeing the C-allocated memory.

Interview question

Which of the following is a significant practical implication of incorporating Cgo into a Go application?

  • a.It restricts the application's deployment to only operating systems that natively support C libraries.
  • b.It automatically converts all C functions into equivalent Go functions at compile time, removing the need for C compilers.
  • c.It introduces a substantial performance overhead for calls between Go and C, making it generally unsuitable for performance-critical inner loops.Correct
  • d.It necessitates manual memory management for all data structures, even those purely in Go.
Why?

The card explicitly states that "The performance overhead of cgo calls can be substantial, making it a poor choice for performance-critical inner loops." Option D is incorrect because Cgo only requires manual memory management for C-allocated memory, not for all Go data structures, which remain managed by Go's garbage collector.

Just read this? Test yourself on what you have been reading.

Read the original → pkg.go.dev

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on go — each one lists the topics its interview covers.

See open roles