Go Cgo: Call C Functions in Go

To call a C interface in Go, you need to use the cgo tool. Here is a simple example demonstrating how to call a function from a library written in C language in Go.

First, create a source file example.c in the C language, containing a simple function hello().

#include <stdio.h>

void hello() {
    printf("Hello from C!\n");
}

Next, create a Go language source file named main.go. In this file, use the cgo tool to import a C language header file and call the C function hello().

package main

// #include "example.c"
import "C"

func main() {
    C.hello()
}

Next, execute the following command in the command line to compile and run this program:

go run main.go

You will see the output “Hello from C!” which indicates that Go successfully called a function from C.

bannerAds