What Is Cgo and How to Call C Code from Go

Cgo is a tool for calling C functions from Go by wrapping C headers in comments before importing the special "C" package.

Cgo is a tool that allows Go code to call C functions and use C libraries by generating wrapper code during compilation. To call C code, define the C header includes and function declarations in a comment block immediately preceding import "C", then reference C symbols using the C. prefix in your Go code.

package main

/*
#include <stdio.h>
*/
import "C"

func main() {
	C.printf("Hello from C\n")
}

If linking against an external library, add #cgo LDFLAGS: -l<library_name> in the comment block before import "C".