无法在 Golang 应用程序中使用已使用 cgo 编译的 C 库?
Cannot use already compiled C library using cgo in Golang application?
我正在尝试用 Golang 包装一个 C 库。我试图在已编译的库中调用 C 函数。我有一个 .a
文件和一个 .so
库文件。
我需要将库文件放在哪里,我如何告诉 cgo
我正在使用这些库?
我是 C 语言的新手,如有帮助将不胜感激。
我将用这个例子来解释它:
首先构建 libhello.a
使用 ./libs/m.c
:
#include <stdint.h>
extern uint64_t Add(uint64_t a, uint64_t b) {
return a + b;
}
对于此测试样本 libhello.a
在 ./libs/
内:
m.go
└───libs
m.c
libhello.a
然后 go build
这个 m.go
工作样本:
package main
//#cgo LDFLAGS: -L${SRCDIR}/libs -lhello
//#include <stdint.h>
//extern uint64_t Add(uint64_t a, uint64_t b);
import "C"
import (
"fmt"
)
func main() {
fmt.Println(C.Add(C.uint64_t(10), C.uint64_t(20))) // 30
}
输出:
30
When the cgo directives are parsed, any occurrence of the string
${SRCDIR} will be replaced by the absolute path to the directory
containing the source file. This allows pre-compiled static libraries
to be included in the package directory and linked properly. For
example if package foo is in the directory /go/src/foo:
// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
Will be expanded to:
// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
我正在尝试用 Golang 包装一个 C 库。我试图在已编译的库中调用 C 函数。我有一个 .a
文件和一个 .so
库文件。
我需要将库文件放在哪里,我如何告诉 cgo
我正在使用这些库?
我是 C 语言的新手,如有帮助将不胜感激。
我将用这个例子来解释它:
首先构建 libhello.a
使用 ./libs/m.c
:
#include <stdint.h>
extern uint64_t Add(uint64_t a, uint64_t b) {
return a + b;
}
对于此测试样本 libhello.a
在 ./libs/
内:
m.go
└───libs
m.c
libhello.a
然后 go build
这个 m.go
工作样本:
package main
//#cgo LDFLAGS: -L${SRCDIR}/libs -lhello
//#include <stdint.h>
//extern uint64_t Add(uint64_t a, uint64_t b);
import "C"
import (
"fmt"
)
func main() {
fmt.Println(C.Add(C.uint64_t(10), C.uint64_t(20))) // 30
}
输出:
30
When the cgo directives are parsed, any occurrence of the string ${SRCDIR} will be replaced by the absolute path to the directory containing the source file. This allows pre-compiled static libraries to be included in the package directory and linked properly. For example if package foo is in the directory /go/src/foo:
// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
Will be expanded to:
// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo