Golang如何将运行时链接到共享库

Golang如何将运行时链接到共享库 我正在尝试为共享的Go库添加模块数据,但遇到了这个错误。有人能建议如何解决这个错误吗?

/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/x86_64-linux-gnu-ld: /tmp/go-link-540345387/go.o: relocation R_X86_64_PC32 against symbol `runtime.firstmoduledata’ can not be used when making a shared object; recompile with -fPIC
/usr/bin/x86_64-linux-gnu-ld: final link failed: Bad value
collect2: error: ld returned 1 exit status

我尝试在 go build 命令中传递 -ldflags '-extldflags "-fPIC"' 参数,但错误依旧。


更多关于Golang如何将运行时链接到共享库的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

在创建共享库时,它也会编译运行时代码。它是如何编译运行时代码的?我可以在编译运行时代码时传递fpic吗?

更多关于Golang如何将运行时链接到共享库的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这个错误是因为Go运行时没有被编译为位置无关代码(PIC)。要解决这个问题,需要重新编译Go运行时使其支持PIC。

以下是具体步骤:

  1. 重新编译Go工具链
# 下载Go源码
git clone https://go.googlesource.com/go
cd go/src

# 使用PIC标志编译Go
CGO_ENABLED=1 GOEXPERIMENT=cgocheck2 ./make.bash
  1. 构建共享库时使用正确的标志
// 示例:构建C共享库
//go:build cshared

package main

import "C"

//export MyFunction
func MyFunction() {
    // 你的代码
}

func main() {
    // 空main函数,用于构建共享库
}

构建命令:

go build -buildmode=c-shared -o libmylib.so
  1. 如果使用外部链接,确保传递正确的标志:
go build -buildmode=c-shared -ldflags '-linkmode=external -extldflags "-fPIC"' -o libmylib.so
  1. 检查你的Go版本,某些旧版本可能需要额外的环境变量:
# 对于某些情况,可能需要设置
export CGO_CFLAGS="-fPIC"
export CGO_LDFLAGS="-fPIC"

# 然后重新构建
go build -buildmode=c-shared -o libmylib.so

关键点是确保整个工具链(包括运行时)都使用PIC编译。如果问题仍然存在,可能需要检查系统是否安装了正确版本的gcc和binutils。

回到顶部