Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface Go with C libraries

Tags:

How does one interface a Go program with a C library?

I've been browsing Go's source code but I still didn't figured it out. If someone has already done so, could you share, please?

UPDATED: Thanks to @fserb, I am posting some documentation from the Go sources:

Cgo enables the creation of Go packages that call C code.

Usage: cgo [compiler options] file.go

The compiler options are passed through uninterpreted when invoking gcc to compile the C parts of the package.

The input file.go is a syntactically valid Go source file that imports the pseudo-package "C" and then refers to types such as C.size_t, variables such as C.stdout, or functions such as C.putchar.

If the import of "C" is immediately preceded by a comment, that comment is used as a header when compiling the C parts of the package. For example:

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

Cgo transforms the input file into four output files: two Go source files, a C file for 6c (or 8c or 5c), and a C file for gcc.

The standard package makefile rules in Make.pkg automate the process of using cgo. See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples.

Cgo does not yet work with gccgo.

like image 758
jldupont Avatar asked Nov 19 '09 02:11

jldupont


People also ask

Can you use C libraries in Go?

Go allows linking against C libraries or pasting in in-line code.

What is C Go?

Introduction. Cgo lets Go packages call C code. Given a Go source file written with some special features, cgo outputs Go and C files that can be combined into a single Go package.


1 Answers

Check cgo. Also, take a look at misc/cgo/gmp on the Go source code for an example code on how to wrap a C library in Go.

like image 70
fserb Avatar answered Dec 18 '22 06:12

fserb