无法在 Golang 应用程序中使用 cgo 编译的 C 库?

我正在尝试在 Golang 中包装一个 C 库。我正在尝试在已编译的库中调用 C 函数。我有一个.a文件和一个.so库文件。

我需要在哪里放置库文件以及如何判断cgo我正在使用这些库?

当谈到 C 时,我是一个新手。任何帮助将不胜感激。


德玛西亚99
浏览 211回答 1
1回答

芜湖不芜

我将用这个示例来解释它:第一次构建libhello.a使用./libs/m.c:#include <stdint.h>&nbsp;extern uint64_t Add(uint64_t a, uint64_t b) {&nbsp; &nbsp; return a + b;}对于这个测试样本libhello.a在里面./libs/:m.go└───libs&nbsp; &nbsp; m.c&nbsp; &nbsp; 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 (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; fmt.Println(C.Add(C.uint64_t(10), C.uint64_t(20))) // 30}输出:30解析 cgo 指令时,任何出现的字符串 ${SRCDIR} 都将替换为包含源文件的目录的绝对路径。这允许将预编译的静态库包含在包目录中并正确链接。例如,如果包 foo 在目录 /go/src/foo 中:// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo将扩展为:// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go