Cargo bench linking problem

I have a github repository showing an awkward linking problem with a c++ library.

In this repository and branch I bulld some rust code, c++ code and Swift code and link it together to an executable. There is also a Criterion benchmark comparing the performance of some functions there in the different language implementations. The curious thing is, if I run

cargo run --release

everything builds and links fine and the resulting executable runs.

But if I do

cargo bench

cargo fails to link the benchmark executable with an error message indicating (and I can see in the linker invocation line that this is indeed the case) that the c++ library isn't linked into the executable.

My current workaround is to make the c++ code a shared library. But I consider this behaviour to be a bug. If cargo run works (cargo build as well), cargo bench should work either.

Or what am I doing wrong here?

This is on MacOS Sonoma on Apple Silicon.

On my system, trap_cpp::trap_cpp_dp can be called succesfully from both the main binary and the benchmark binary. But trap_cpp::trap_cpp causes a link error when called from either main.rs or the benchmark.

Adding this to trap_cpp/build.rs seems to fix the problem:

    println!("cargo:rustc-link-lib=stdc++");

(Or you can use link-cplusplus.)

Thank you. I opted for link-cplusplus which works. Things build fine now on macOS and Linux.

However, it is still strange that there is a different linker invocation with cargo run and cargo bench.

As far as I could tell, the only difference was that the benchmark called trap_cpp::trap_cpp while main.rs did not. If I changed the two files to have identical code, they behaved identically.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.