1 回答

TA貢獻1772條經驗 獲得超5個贊
我運行 go run test.go:我有以下輸出:
# command-line-arguments
/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_51159acd5c8e_Cfunc_hello':
/tmp/go-build/cgo-gcc-prolog:48: undefined reference to `hello'
collect2: error: ld returned 1 exit status
我們可以使用以下代碼生成等效的錯誤消息。
package main
/*
#include <math.h>
*/
import "C"
import "fmt"
func main() {
cube2 := C.pow(2.0, 3.0)
fmt.Println(cube2)
}
輸出:
$ go run cube2.go
# command-line-arguments
/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_f6c6fa139eda_Cfunc_pow':
/tmp/go-build/cgo-gcc-prolog:53: undefined reference to `pow'
collect2: error: ld returned 1 exit status
$
在這兩種情況下,ld(鏈接器)在查看通常的位置后都找不到 C 函數:undefined reference to 'pow'或undefined reference to 'hello'。
讓我們告訴您在 C庫中cgo哪里可以找到 C函數:。powmathm
對于cgo,使用ld標志,
#cgo LDFLAGS: -lm
GCC:3.14 鏈接選項
-llibrary
Search the library named library when linking.
更新之前的代碼,
package main
/*
#cgo LDFLAGS: -lm
#include <math.h>
*/
import "C"
import "fmt"
func main() {
cube2 := C.pow(2.0, 3.0)
fmt.Println(cube2)
}
輸出:
$ go run cube2.go
8
$
這說明了一個基本cgo原則:包含 C 庫的 C 頭文件并指向 C 庫的位置。
- 1 回答
- 0 關注
- 152 瀏覽
添加回答
舉報