Some examples to understand the workflow of using Go C Bindings

What

In Go you can call C programs and functions using cgo. This way you can easily create C bindings to other applications or libraries that provides C API.

How

All you need to do is to add a import "C" at the beginning of your Go program just after including your C program:

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

With the previous example you can use the stdio package in Go.

If you need to use an app that is on your same folder, you use the same syntax than in C (with the " instead of <>)

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

IMPORTANT: Do not leave a newline between the include and the import "C" statements or you will get this type of errors on build:

# command-line-arguments
could not determine kind of name for C.Hello
could not determine kind of name for C.sum

The example

On this folder you can find an example of C bindings. We have two very simple C “libraries” called hello.c:

//hello.c
#include <stdio.h>

void Hello(){
    printf("Hello world\\n");
}

That simply prints “hello world” in the console and sum.c

//sum.c
#include <stdio.h>

int sum(int a, int b) {
    return a + b;
}

…that takes 2 arguments and returns its sum (do not print it).

We have a main.go program that will make use of this two files. First we import them as we mentioned before:

//main.go
package main

/*
  #include "hello.c"
  #include "sum.c"
*/
import "C"

Hello World!