![](/img/trans.png)
[英]How do you use Golang's cgo with C libraries that link to math.h?
[英]How to use external .c files with CGO?
在import "C"
上方的注釋中編寫一些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())
}
它工作正常:
$ go install
$ foo
forty-two == 42
但是,它自己的.c文件中的C代碼:
// foo.c
int fortythree() {
return 43;
}
...引用自Go:
// foo.go
func main() {
fmt.Printf("forty-two == %d\n", C.fortytwo())
fmt.Printf("forty-three == %d\n", C.fortythree())
}
...不起作用:
$ go install
# foo
could not determine kind of name for C.fortythree
C頭文件foo.h丟失:
// foo.h
int fortythree();
像這樣從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())
}
看哪,foo.h的力量:
$ go install
$ foo
forty-two == 42
forty-three == 43
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.