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.
Go allows linking against C libraries or pasting in in-line code.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With