Free — no signup required

CGO: The Bridge to C

1 min read

Calling C from Go

Sometimes the library you need only exists in C. ImageMagick for image processing, libsqlite3 for embedded databases, OpenSSL for specific crypto operations, CUDA for GPU access — these have no pure-Go equivalents, or the pure-Go alternatives lack critical features.

CGO is Go's Foreign Function Interface (FFI). It lets you embed C code directly in a Go source file using a special comment block immediately before import "C":

package main

/*
#include <math.h>
#include <stdlib.h>

// You can also define C functions inline here
int add(int a, int b) {
    return a + b;
}
*/
import "C"
import "fmt"

func main() {
    // Call the C standard library sqrt function
    result := C.sqrt(C.double(16.0))
    fmt.Printf("sqrt(16) = %v\n", result) // 4

    // Call our inline C function
    sum := C.add(C.int(3), C.int(4))
    fmt.Printf("3 + 4 = %v\n", sum) // 7
}

When you run go build, the toolchain detects import "C", invokes gcc (or clang) to compile the C portions, and links the resulting object files into your Go binary. The C. prefix is how you reference C types and functions from Go code.

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