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

我在 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-build1175764972

mkdir -p $WORK/b001/

cd /home/helloworld

TERM='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.go

cd $WORK

gcc -fno-caret-diagnostics -c -x c - -o /dev/null || true

gcc -Qunused-arguments -c -x c - -o /dev/null || true

gcc -fdebug-prefix-map=a=b -c -x c - -o /dev/null || true

gcc -gno-record-gcc-switches -c -x c - -o /dev/null || true

cd $WORK/b001


ITMISS
浏览 142回答 1
1回答

jeck猫

我能够重现并修复这个问题。还有一些额外的问题。从专注于跑步开始go build:好的所以 go 编译器找到了头文件,但是找不到共享库。我认为您稍微修改了问题的代码,这不是问题,但-Lin的路径LDFLAGS必须是:相对于源目录使用${SRCDIR}绝对路径完全避免这种情况并利用 pkg-config 我只是使用包含so文件的相对目录作为-L.好的,除此之外,您还必须-l在 LDFLAGS 中给出一个参数,以在您指向的路径中找到文件(即:libvendera.so需要-lvendora)。一旦go build工作,您的应用程序仍然需要知道文件的so运行位置(因此是共享库)。为此,您可能需要设置LD_LIBRARY_PATH并指向包含so文件的目录,就像您对-L.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go