为了账号安全,请及时绑定邮箱和手机立即绑定

Cgo:对 [C 函数] 的未定义引用

Cgo:对 [C 函数] 的未定义引用

Go
ITMISS 2022-11-28 10:36:50
我在 docker 容器 ( golang:1.18-bullseye) 中运行一个 go 程序。我试过用go run main.go和运行它go run .我的代码看起来像这样,两个头文件都位于IncludeCFLAGS 中给定的目录中:/*#cgo LDFLAGS: -Lvendor/MyCoolLibrary/1.14.2/Bin/Linux/libSDK-Linux-Shipping.so#cgo CFLAGS: -I vendor/MyCoolLibrary/1.14.2/Include/#include "my_cool_sdk.h"#include "my_cool_logging.h"*/import "C"import (    "fmt"    "log"    "os"    "runtime")func main() {ret := C.MyCoolFunc()}当我运行此代码时,我收到此错误消息:/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_6bb9bcf96ac6_Cfunc_MyCoolFunc':/tmp/go-build/cgo-gcc-prolog:110: undefined reference to `MyCoolFunc'我怎样才能解决这个问题?编辑:我将标题更改为:/*#cgo LDFLAGS: -L${SRCDIR}/vendor/MyCoolLibrary/1.14.2/Bin/Linux/libSDK-Linux-Shipping.so -lSDK-Linux-Shipping#cgo CFLAGS: -I ${SRCDIR}/vendor/MyCoolLibrary/1.14.2/Include/#include "my_cool_sdk.h"#include "my_cool_logging.h"*/然后运行go build -x .,这是输出:WORK=/tmp/go-build1175764972mkdir -p $WORK/b001/cd /home/helloworldTERM='dumb' CGO_LDFLAGS='"-g" "-O2" "-L/home/helloworld/vendor/MyCoolLibrary/1.14.2/Bin/Linux/libSDK-Linux-Shipping.so" "-lSDK-Linux-Shipping"' /usr/local/go/pkg/tool/linux_amd64/cgo -objdir $WORK/b001/ -importpath go-sandbox -- -I $WORK/b001/ -g -O2 -I ./vendor/MyCoolLibrary/1.14.2/Include/ ./main.gocd $WORKgcc -fno-caret-diagnostics -c -x c - -o /dev/null || truegcc -Qunused-arguments -c -x c - -o /dev/null || truegcc -fdebug-prefix-map=a=b -c -x c - -o /dev/null || truegcc -gno-record-gcc-switches -c -x c - -o /dev/null || truecd $WORK/b001
查看完整描述

1 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

我能够重现并修复这个问题。还有一些额外的问题。从专注于跑步开始go build

好的所以 go 编译器找到了头文件,但是找不到共享库。我认为您稍微修改了问题的代码,这不是问题,但-Lin的路径LDFLAGS必须是:

  • 相对于源目录使用${SRCDIR}

  • 绝对路径

  • 完全避免这种情况并利用 pkg-config 我只是使用包含so文件的相对目录作为-L.

好的,除此之外,您还必须-l在 LDFLAGS 中给出一个参数,以在您指向的路径中找到文件(即:libvendera.so需要-lvendora)。

一旦go build工作,您的应用程序仍然需要知道文件的so运行位置(因此是共享库)。为此,您可能需要设置LD_LIBRARY_PATH并指向包含so文件的目录,就像您对-L.


查看完整回答
反对 回复 2022-11-28
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信