交叉编译时动态链接Go程序

问题描述 投票:0回答:2

如何交叉编译Go程序并仍然保留libc的动态链接?

上下文:编译主机是macOS M1,目标是Linux amd64。

default
结果是静态链接的。但是我仍然想要动态链接,特别是 libc 部分具有 LD_PRELOAD 能力)。

尝试像这样强制动态链接

❯ CGO_ENABLED=1 GOARCH=amd64 GOOS=linux go build -o main cmd/server/main.go

# runtime/cgo
linux_syscall.c:67:13: error: call to undeclared function 'setresgid'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
linux_syscall.c:67:13: note: did you mean 'setregid'?
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/unistd.h:593:6: note: 'setregid' declared here
linux_syscall.c:73:13: error: call to undeclared function 'setresuid'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
linux_syscall.c:73:13: note: did you mean 'setreuid'?
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/unistd.h:595:6: note: 'setreuid' declared here

有什么建议可以解决这个问题吗?非常感谢

go cgo ld-preload
2个回答
1
投票

根据文档: 将 cgo 与 go 命令一起使用

仅指定 GOOS 和 GOARCH 是不够的,还需要指定 CC_FOR_TARGET 或 CC_FOR_${GOOS}_${GOARCH}。 检查这个:

交叉编译时,必须指定一个C交叉编译器供cgo使用。您可以通过在使用 make.bash 构建工具链时设置通用 CC_FOR_TARGET 或更具体的 CC_FOR_${GOOS}_${GOARCH} (例如 CC_FOR_linux_arm)环境变量来完成此操作,也可以随时设置 CC 环境变量你运行 go 工具。


0
投票

感谢@Kalis的建议。我错过的是交叉编译器。

  1. 安装交叉编译器gcc
brew tap SergioBenitez/osxct
brew install x86_64-unknown-linux-gnu

来源:https://github.com/SergioBenitez/homebrew-osxct 另一个来源:https://github.com/messense/homebrew-macos-cross-toolchains(尚未测试)。

  1. 编译时提供CC
❯ CC=x86_64-unknown-linux-gnu-gcc CGO_ENABLED=1 GOARCH=amd64 GOOS=linux go build main.go
© www.soinside.com 2019 - 2024. All rights reserved.