Go 1.5發佈後,其包含一個特性:能夠編譯生成C語言動態連接庫或靜態庫。本文給出了示例代碼和用法。golang
go build
和go install
命令,能夠使用參數 -buildmode
來指定生成哪一種類型的二進制目標文件。請見https://golang.org/cmd/go/#Description of build modes 詳細說明。測試
當前咱們使用 -buildmode=c-archive
來示例和測試。ui
Golang源文件:spa
// file hello.go package main port "C" import "fmt" //export SayHello func SayHello(name string) { fmt.Printf("func in Golang SayHello says: Hello, %s!\n", name) } //export SayHelloByte func SayHelloByte(name []byte) { fmt.Printf("func in Golang SayHelloByte says: Hello, %s!\n", string(name)) } //export SayBye func SayBye() { fmt.Println("func in Golang SayBye says: Bye!") } func main() { // We need the main function to make possible // CGO compiler to compile the package as C shared library }
使用命令go build -buildmode=c-archive -o libhello.a hello.go
能夠生成一個C語言靜態庫libhello.a
和頭文件libhello.h
。 而後咱們再寫個C語言程序來調用這個庫,以下:code
// file hello.c #include <stdio.h> #include "libhello.h" int main() { printf("This is a C Application.\n"); GoString name = {(char*)"Jane", 4}; SayHello(name); GoSlice buf = {(void*)"Jane", 4, 4}; SayHelloByte(buf); SayBye(); return 0; }
使用命令gcc -o hello hello.c libhello.a -pthread
來編譯生成一個可執行文件hello
。執行命令以下:blog
$ go build -buildmode=c-archive -o libhello.a hello.go $ gcc -o hello hello.c libhello.a -pthread $ ./hello This is a C Application. func in Golang SayHello says: Hello, Jane! func in Golang SayHelloByte says: Hello, Jane! func in Golang SayBye says: Bye!
備註:目前Golang還不支持將一個struct結構導出到C庫中。ip