gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:05:49 24 4
gpt4 key购买 nike

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

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

我是 C 语言的新手。如有任何帮助,我们将不胜感激。

最佳答案

我将用这个示例来解释它:

首先使用./libs/m.c构建libhello.a:

#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 应用程序中使用已使用 cgo 编译的 C 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39251045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com