Cgo: First steps tutorial

suggest change

Some examples to understand the workflow of using Go C Bindings

What

Go can call C functions through cgo. This makes it possible to bind to libraries that provide a C API.

How

Add import "C" immediately after the C preamble:

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

That preamble makes the declarations in stdio.h available through cgo. It is the C header, not a Go package.

If the C file is in the same directory, use quotes instead of angle brackets, as in C:

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

IMPORTANT: Do not leave a blank line between the include comment and import "C", or the build fails with errors like:

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

The example

The example uses two very small C files. hello.c:

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

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

It prints Hello world to the console. sum.c:

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

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

It takes two arguments and returns their sum (it does not print it).

main.go uses both files. Import them in the preamble:

//main.go
package main

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

Hello World!

Now we are ready to use the C programs in our Go app. Let’s first try the Hello program:

//main.go
package main

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

import (
    "errors"
    "log"
)

func main() {
    // Call a void C function.
    err := Hello()
    if err != nil {
        log.Fatal(err)
    }
}

// Hello calls the C function. In the two-result form, cgo returns errno
// as an error. A void C function has no other result, so the first value
// is discarded.
func Hello() error {
    _, err := C.Hello()
    if err != nil {
        return errors.New("error calling Hello function: " + err.Error())
    }

    return nil
}

Run it with go run main.go. The C function prints Hello world.

Sum of ints

Let’s make it a bit more complex by adding a function that sums its two arguments.

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

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

And we’ll call it from our previous Go app.

//main.go
package main

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

import (
    "errors"
    "fmt"
    "log"
)

func main() {
    //Call to void function without params
    err := Hello()
    if err != nil {
        log.Fatal(err)
    }

    //Call to int function with two params
    res, err := makeSum(5, 4)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Sum of 5 + 4 is %d\n", res)
}

// Hello calls the C function. In the two-result form, cgo returns errno
// as an error. A void C function has no other result, so the first value
// is discarded.
func Hello() error {
    _, err := C.Hello()
    if err != nil {
        return errors.New("error calling Hello function: " + err.Error())
    }

    return nil
}

// makeSum calls the C function. Convert Go ints to C.int before the call
// and convert the C.int result back to a Go int. The second result is errno.
func makeSum(a, b int) (int, error) {
    //Convert Go ints to C ints
    aC := C.int(a)
    bC := C.int(b)

    sum, err := C.sum(aC, bC)
    if err != nil {
        return 0, errors.New("error calling Sum function: " + err.Error())
    }

    //Convert C.int result to Go int
    res := int(sum)

    return res, nil
}

makeSum receives two Go int values and converts them with C.int before the call. In the two-result form the call returns the C int and an error that is non-nil when errno is set. Convert the C result with int().

Try running our go app by using go run main.go

$ go run main.go
Hello world
Sum of 5 + 4 is 9

Generating a binary

go build (with no file arguments) compiles every .c file in the directory as well as the copies #included from the preamble, so the same symbols are defined twice:

$ go build
# github.com/sayden/c-bindings
/tmp/go-build329491076/github.com/sayden/c-bindings/_obj/hello.o: In function `Hello':
../../go/src/github.com/sayden/c-bindings/hello.c:5: multiple definition of `Hello'
/tmp/go-build329491076/github.com/sayden/c-bindings/_obj/main.cgo2.o:/home/mariocaster/go/src/github.com/sayden/c-bindings/hello.c:5: first defined here
/tmp/go-build329491076/github.com/sayden/c-bindings/_obj/sum.o: In function `sum':
../../go/src/github.com/sayden/c-bindings/sum.c:5: multiple definition of `sum`
/tmp/go-build329491076/github.com/sayden/c-bindings/_obj/main.cgo2.o:/home/mariocaster/go/src/github.com/sayden/c-bindings/sum.c:5: first defined here
collect2: error: ld returned 1 exit status

Pass the Go file explicitly so those sibling .c files are not compiled again:

$ go build main.go
$ ./main
Hello world
Sum of 5 + 4 is 9

Remember that you can provide a name to the binary file by using -o flag go build -o my_c_binding main.go

I hope you enjoyed this tutorial.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents