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")
}
- Write C code or
#includedirectives in a comment block immediately beforeimport "C". - Add
import "C"to your import list to enable cgo processing. - Call C functions using the
C.prefix, such asC.printforC.malloc. - Compile the file with
go buildto generate the necessary C wrapper and link the binary.