Simple example
Cgo.go
package main//#include <stdio.h>//void callC() {// printf("Calling C code!\n");//}import "C"import "fmt"func main() { fmt.Println("A Go statement!") C.callC() fmt.Println("Another Go statement!")}
Slightly complex example
CallC.h
#ifndef CALLC_H#define CALLC_Hvoid cHello();void printMessage(char* message);#endif
Callc.c
#include <stdio.h>#include "callC.h"void cHello() { printf("Hello from C!\n");}void printMessage(char* message) { printf("Go send me %s\n", message);}
Callc.go
package main//#cgo CFLAGS:-i${srcdir}/callclib//#cgo ldflags: ${srcdir}/callc.a//#include <stdlib.h>//#include <callc.h>import "C" Import ("FMT" "unsafe") Func main () {FMT. Println ("Going to call a C function!") C.chello () fmt. Println ("Going to call another C function!") Mymessage: = C.cstring ("This is mihalis!") Defer C.free (unsafe. Pointer (Mymessage)) c.printmessage (mymessage) fmt. Println ("All Perfectly done!")}