How to Call C from Go with Cgo

Call C functions from Go by adding a C preamble comment, importing "C", and using the C. prefix to invoke functions.

You call C functions from Go by defining a C preamble in a comment block, importing the pseudo-package "C", and prefixing C identifiers with C. in your Go code.

package main

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

func main() {
	C.printf("Hello from C\n")
}
  1. Write C code or #include directives in a comment block immediately before import "C".
  2. Add import "C" to your import list to enable cgo processing.
  3. Call C functions using the C. prefix, such as C.printf or C.malloc.
  4. Compile the file with go build to generate the necessary C wrapper and link the binary.