【问题标题】:Cross compile a shared Library under Linux for windows在Linux for windows下交叉编译一个共享库
【发布时间】:2021-04-26 19:36:54
【问题描述】:

我想得到一个windows-DLL,但我想在Ubuntu-Linux下编译。

构建一个可执行文件很简单:env GOOS=windows GOARCH=386 go build wrapper.go 生成一个 wrapper.exe,其行为符合预期。

但是使用env GOOS=windows GOARCH=386 go build -buildmode=c-shared wrapper.go 构建DLL 会导致错误:

running gcc failed: exit status 1
gcc: error: unrecognized command line option ‘-mconsole’; did you mean ‘--compile’?

我不希望在windows下安装和运行go,因为我的完整工具链是在Ubuntu下运行的

go version go1.15.6 linux/amd64

【问题讨论】:

标签: go cross-compiling


【解决方案1】:

如果您将-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 是用-extld=gcc 调用的,我们从go doc cmd/link 收集到

-extld 链接器
设置外部链接器(默认“clang”或“gcc”)。

我的猜测是,为了生成与 C 兼容的动态库,Go 工具链依赖于外部 C 链接器,这是由 cgo machinery 执行的——实际上在 documentation of -buildmode=c-shared 中有一个提示:

-buildmode=c-shared
构建列出的主包,以及它导入的所有包,
到 C 共享库中。唯一可调用的符号将
是那些使用 cgo //export 注释导出的函数。
只需要列出一个主包。

因此我的猜测是,为了做你想做的事,你必须:

  • 安装支持 Windows/i386 的交叉编译器 - 您可以从 this 开始。
  • 按照cgo docs 中的说明,在调用go build 之前设置环境,以便Go 工具链调用Windows 特定的链接器。
  • 通过使用-x 命令行选项运行go build 来验证它是否有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2015-07-21
    • 2022-01-03
    • 2017-05-24
    相关资源
    最近更新 更多