rust-cross / cargo-zigbuild

Compile Cargo project with zig as linker
MIT License
1.45k stars 52 forks source link

library compiled with zigbuild cannot be statically linked by CGO #267

Closed hellodword closed 1 month ago

hellodword commented 1 month ago

I am attempting to wrap a Rust library and compile it on Linux, then statically link it on both Linux and Windows using CGO.

I plan to use zig cc -target x86_64-windows-gnu for a straightforward cross-build experience.

The source code I'm utilizing is https://github.com/hellodword/rust-plus-golang/tree/issue-1

The compile command on Linux is cargo zigbuild --release --target x86_64-pc-windows-gnu.

The CGO compile command is CGO_ENABLED=1 CC="zig cc -target x86_64-windows-gnu" GOOS=windows go build <...>.

I've searched extensively and tried many approaches, but I keep encountering errors:

  1. With the latest stable or nightly zig (0.13.0 or 0.14.0-dev.850+ddcb7b1c1), I consistently face errors when compiling the library:
  = note: warning: ignoring deprecated linker optimization setting '1'
          error: unable to find dynamic system library 'msvcrt' using strategy 'paths_first'. searched paths:
  1. Using zig 0.10.1, I can successfully compile the library, but I encounter an error when cross-building the CGO:
/usr/local/go/pkg/tool/linux_amd64/link: running zig failed: exit status 1
lld-link: error: duplicate symbol: ___chkstk_ms
>>> defined at compiler_rt.lib(compiler_rt.lib.obj)
>>> defined at src/x86_64.rs:18
>>>            libhello-win.a(compiler_builtins-6c9e2f948258138b.compiler_builtins.2bfaa9d19ad82e39-cgu.135.rcgu.o)

Here is the reproduce:

git clone -b issue-1 https://github.com/hellodword/rust-plus-golang
cd rust-plus-golang

docker run --rm -it -v "$(pwd)":/io -w /io messense/cargo-zigbuild bash

# install Go
curl -fSL --output /tmp/go1.22.6.linux-amd64.tar.gz https://go.dev/dl/go1.22.6.linux-amd64.tar.gz && \
    tar -C /usr/local -xzf /tmp/go1.22.6.linux-amd64.tar.gz
export PATH="$PATH:/usr/local/go/bin"
go version

make build-static

make build-static-windows

Any ideas?

messense commented 1 month ago

See https://github.com/ziglang/zig/issues/15107

IMHO, zig cc isn't in good shape for windows gnu target yet (for example #251), it's better to reproduce your issue using zig cc directly and report any problems to zig to hopefully get it fixed in upstream.

hellodword commented 1 month ago

See https://github.com/ziglang/zig/issues/15107

I think the 0.14.0-dev.850+ddcb7b1c1 contains the zig PR #20138, it brings new issue of missing msvcrt.

https://github.com/ziglang/zig/commits/ddcb7b1c11f88c4ae150b36807033060a469dcb5/?after=ddcb7b1c11f88c4ae150b36807033060a469dcb5+600

it's better to reproduce your issue using zig cc directly and report any problems to zig to hopefully get it fixed in upstream

Got it, thanks!