gpt4 book ai didi

go - cgo(golang): error: underfined reference to 'hello'

转载 作者:IT王子 更新时间:2023-10-29 02:13:45 24 4
gpt4 key购买 nike

我只是写了一个非常简单的demo来测试用cgo(golang)加载共享库,代码如下:

xxx.h

#pragma once
void myprint(const char *str);

xxx.c

#include "xxx.h"
#include <stdio.h>
void myprint(const char *str) {
printf("%s\n",str);
}

构建共享库:

gcc -fPIC -shared xxx.c -o libxxx.so

好的,从这里开始一切正常。

现在,使用cgo加载libxxx.so,并使用myprint函数:

package main

/*
#include <stdio.h>
#cgo linux CFLAGS: -I../../include
#cgo linux LDFLAGS: -L../../lib/linux -lxxx
#include "xxx.h"
*/
import "C"

funct main() {
C.myprint(C.CString("xxx"))
}

然后,构建 go 演示:

go build test.go

正如我的标题所示:

error: undefined reference to 'myprint'

我确保lib/head文件的路径是正确的,谁能帮我找到原因?谢谢。

最佳答案

相对路径在构建上下文中不起作用,因为构建发生在与源文件不同的目录中。

您有几种选择来提供绝对路径:

  • 您可以在源代码中使用绝对路径
  • 您可以使用 pkg-config 提供绝对路径
  • 您可以使用 CGO_CFLAGSCGO_LDFLAGS 环境变量
  • 您可以在源代码的 #cgo 行中使用 ${SRCDIR} 变量。

参见 cgo documentation了解更多详情

关于go - cgo(golang): error: underfined reference to 'hello' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38202761/

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