从amd64(linux)到arm64(linux)的cgo交叉编译

ttcibm8c  于 2023-02-07  发布在  Linux
关注(0)|答案(3)|浏览(975)

我正在尝试使用基于arm64的so从"amd64"构建一个"arm64"架构的go代码。当我用共享库构建go代码时,我得到了下面提到的错误。有人能帮助我吗?
版本:Linux/amd64操作系统
gcc版本:gcc版本7.3.0(Ubuntu 7.3.0 - 16.04版本)
转到环境:

GOARCH="arm64"
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
CGO_ENABLED="1"

错误:go生成hello。go

# runtime/cgo
gcc_arm64.S: Assembler messages:
gcc_arm64.S:27: Error: no such instruction: `stp x19,x20,[sp,'
gcc_arm64.S:28: Error: no such instruction: `stp x21,x22,[sp,'
gcc_arm64.S:29: Error: no such instruction: `stp x23,x24,[sp,'
gcc_arm64.S:30: Error: no such instruction: `stp x25,x26,[sp,'
gcc_arm64.S:31: Error: no such instruction: `stp x27,x28,[sp,'
gcc_arm64.S:32: Error: no such instruction: `stp x29,x30,[sp,'
gcc_arm64.S:33: Error: too many memory references for `mov'
gcc_arm64.S:35: Error: too many memory references for `mov'
gcc_arm64.S:36: Error: too many memory references for `mov'
gcc_arm64.S:37: Error: too many memory references for `mov'
gcc_arm64.S:39: Error: no such instruction: `blr x20'
gcc_arm64.S:40: Error: no such instruction: `blr x19'
gcc_arm64.S:42: Error: no such instruction: `ldp x29,x30,[sp],'
gcc_arm64.S:43: Error: no such instruction: `ldp x27,x28,[sp],'
gcc_arm64.S:44: Error: no such instruction: `ldp x25,x26,[sp],'
gcc_arm64.S:45: Error: no such instruction: `ldp x23,x24,[sp],'
gcc_arm64.S:46: Error: no such instruction: `ldp x21,x22,[sp],'
gcc_arm64.S:47: Error: no such instruction: `ldp x19,x20,[sp],'

Go代码:

package main
/*
#cgo CFLAGS: -I./cgolang/include
#cgo LDFLAGS: -L./cgolang/lib  -laxxxxxx
#include "axxxxxx.h"
*/
import "C"
import "fmt"

func main() {
fmt.Printf("hello, world\n")
}
kpbpu008

kpbpu0081#

当我需要用cgo构建一个静态Go二进制文件时,我遇到了类似的问题,这个二进制文件最终将在 * arm 64 * 架构的 alpine 容器中运行,但必须在 x86_64 架构的 golang:alpine 容器中构建(我无法控制CI/CD runner架构)。
我像@jesse的答案一样解决了这个问题,但为了完整起见,我想包含一个示例,因为我不知道从哪里获得交叉编译器,以及使用其中的哪些文件。下面是一个示例,在容器用户的主目录中下载/提取CC,并在基于/usr/src/example的go构建中使用它,生成一个名为 exampleApp 的可执行文件。

wget -P ~ https://musl.cc/aarch64-linux-musl-cross.tgz
tar -xvf ~/aarch64-linux-musl-cross.tgz -C ~
cd /usr/src/example
GOOS=linux GOARCH=arm64 CGO_ENABLED=1 CC=~/aarch64-linux-musl-cross/bin/aarch64-linux-musl-gcc go build -o exampleApp -a -ldflags=-extldflags=-static .

exe输出上运行file验证了它是为aarch 64静态链接的,然后我能够在其他地方的arm 64 alpine容器中运行它。

nnsrf1az

nnsrf1az2#

我像这样链接了数学库#cgo LDFLAGS:-L./cgolang/库-lp线程-lm
如果你的共享库是由第三方提供的,请让他们帮你解决

s6fujrry

s6fujrry3#

env CGO_ENABLED=1 GOOS=linux GOARCH=arm64 CC=/path/to/your/arm64/gcc go build hello.go

你会发现同样的问题https://github.com/golang/go/issues/8161

相关问题