linux下交叉编译windows下的共享库
我想得到一个 windows-DLL,但我想在 Ubuntu-Linux 下编译它。
构建一个 Executable 很简单:env GOOS=windows GOARCH=386 go build wrapper.go生成一个wrapper.exe, 行为如预期。
但是构建一个 DLL 会env GOOS=windows GOARCH=386 go build -buildmode=c-shared wrapper.go导致错误:
running gcc failed: exit status 1
gcc: error: unrecognized command line option ‘-mconsole’; did you mean ‘--compile’?
我不想go在 windows 下安装和运行,因为我的完整工具链是在 Ubuntu 下运行的
go version go1.15.6 linux/amd64
回答
如果您将-x调用传递给go build -buildmode=c-shared ...,您会注意到在该模式下,Go 工具链中的链接器调用外部 C 链接器;例如,在带有 Go 1.15.x 的 GNU/Linux 上,我有:
mkdir -p $WORK/b001/exe/
cd $WORK/b001/exe/
/home/username/devel/golang-1.15.6/pkg/tool/linux_amd64/link -o cshared.dll -importcfg $WORK/b001/importcfg.link -buildmode=c-shared -buildid=OJVN3iT0GI_DEAMVbLDu/o9eT_YGfUiRe07beNQAA/-xRRfDcM8nVc03rltdqz/OJVN3iT0GI_DEAMVbLDu -extld=gcc $WORK/b001/_pkg_.a
# command-line-arguments
loadinternal: cannot find runtime/cgo
/home/username/devel/golang-1.15.6/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
gcc: error: unrecognized command line option ‘-mconsole’; did you mean ‘--compile’?
请注意,pkg/tool/linux_amd64/link调用 with-extld=gcc和 from go doc cmd/link,我们收集到
-extld linker
设置外部链接器(默认为“clang”或“gcc”)。
我的猜测是,为了生成一个 C 兼容的动态库,Go 工具链依赖于一个外部 C 链接器,这是由cgo机器执行的——实际上在文档中-buildmode=c-shared有一个提示:
-buildmode=c-shared
将列出的主包以及它导入的所有包构建
到 C 共享库中。唯一可调用的符号
是那些使用cgo//export注释导出的函数。
只需要列出一个主要包。
因此,我的猜测是,为了做你想做的事,你必须:
- 安装一个支持 Windows/i386 的交叉编译器——你可以从这个.
go build按照cgo文档中的说明在调用之前设置环境,以便 Go 工具链调用特定于 Windows 的链接器。- 通过
go build使用-x命令行选项运行来验证它是否有效。