在上面的注释中编写一些C代码import "C"很简单:
// foo.go
package main
/*
int fortytwo() {
return 42;
}
*/
import "C"
import "fmt"
func main() {
fmt.Printf("forty-two == %d\n", C.fortytwo())
fmt.Printf("forty-three == %d\n", C.fortythree())
}
Run Code Online (Sandbox Code Playgroud)
它工作正常:
$ go install
$ foo
forty-two == 42
Run Code Online (Sandbox Code Playgroud)
但是,C代码在它自己的.c文件中:
// foo.c
int fortythree() {
return 43;
}
Run Code Online (Sandbox Code Playgroud)
...从Go引用:
// foo.go
func main() {
fmt.Printf("forty-two == %d\n", C.fortytwo())
fmt.Printf("forty-three == %d\n", C.fortythree())
}
Run Code Online (Sandbox Code Playgroud)
......不起作用:
$ go install
# foo
could not determine kind of name for C.fortythree
Run Code Online (Sandbox Code Playgroud)
缺少C头文件foo.h:
// foo.h
int fortythree();
Run Code Online (Sandbox Code Playgroud)
从Go引用头文件,如下所示:
// foo.go
package main
/*
#include "foo.h"
int fortytwo() {
return 42;
}
*/
import "C"
import "fmt"
func main() {
fmt.Printf("forty-two == %d\n", C.fortytwo())
fmt.Printf("forty-three == %d\n", C.fortythree())
}
Run Code Online (Sandbox Code Playgroud)
看哪,foo.h的力量:
$ go install
$ foo
forty-two == 42
forty-three == 43
Run Code Online (Sandbox Code Playgroud)