dtolnay / cxx

Safe interop between Rust and C++
https://cxx.rs
Apache License 2.0
5.89k stars 336 forks source link

Trick to get bazel to link libstdc++ or libc++ in a rust_binary with cxx? #1399

Open sthornington opened 3 hours ago

sthornington commented 3 hours ago

Hi folks - I'm going to continue banging away on this, but in our bazel build, I have gotten as far as our rust_binary linking simply missing the std c++ library (either libstdc++ for a gcc toolchain or libc++ for a clang toolchain). I feel as though this should have happened magically somehow, by virtue of linking against cc_library targets for my C++ code and the cxx-generated bindings of the ffi module, but it doesn't seem to be happening. I have confirmed that adding e.g. -lc++ to final link line if clang does fix the problem.

What am I missing? I am following the example in rules_rust/examples/crate_universe/using_cxx here: https://github.com/bazelbuild/rules_rust/blob/main/examples/crate_universe/using_cxx/BUILD.bazel

sthornington commented 2 hours ago

In my version of rust_cxx_bridge.bzl I have currently added:

    qc_cc_library(
        name = name,
        srcs = [src + ".cpp"],
        deps = deps + [":%s/include" % name],
        linkstatic = True,
        copts = ["-Wno-dollar-in-identifier-extension"],
        linkopts = ["-lstdc++"],  # INCREDIBLY SUS, why do we need to do this, and should it be -lc++ in the clang toolchain somehow?
    )

This seems to get things to link, but as commented, it seems pretty sus. Additionally, I had to use experimental_use_cc_common_link=1 in my rust_binary call. Shouldn't this be getting added correctly no matter what the cc toolchain is set to (clang vs gcc) simply by having a cc_library as a dep into a binary linking or something ?

sthornington commented 2 hours ago

(noticing now that that experimental flag breaks rust linking of other stuff :( .. going to try adding rustc_flags to the specific rust_binary that is using cxx, but I am curious how other people are doing this.)

sthornington commented 2 hours ago

Hmm the problem seems isolated to compiling on clang on linux, getting this now:

/usr/bin/ld.gold: error: bazel-out/k8-dbg/bin/external/crate_index__cxx-1.0.130/libcxx_cc.a(cxx.o): requires dynamic R_X86_64_32 reloc against '__gxx_personality_v0' which may overflow at runtime; recompile with -fPIC

Bizarre....