Linking to C ++ library with external "C" functions

So, I am writing Rust FFI to the C ++ library, which has an β€œC” extern block with C-style function headers. And my low level FFI builds.

However, when I use my FFI in another project, it does not refer correctly, and I get an undefined reference to the new (), delete () operator, etc.

My question is:

  • I screwed up because it is C ++, and you still cannot associate Rust with C ++?

  • If the application using the FFI library is somehow related to the binding problem, and if so, how?

  • Can my libsomething.a be somehow embedded in these C ++ components, and if so, how? I am currently using the gcc box in general.

  • post your own solution here

+8
source share
2 answers

You need to dynamically reference libstdc++ to get the characters you need for C ++ code. You can tell rustc to do this in your build script:

 extern crate gcc; use std::default::Default; fn main() { gcc::compile_library("libhello.a", &Default::default(), &["cpp/hello.cpp"]); println!("cargo:rustc-flags=-l dylib=stdc++"); } 

See full example on github

For more information on build scripts, see the Shipping Guide .

+5
source

This worked for me on macOS using cmake crate.

 // build.rs extern crate cmake; fn main() { let dst = cmake::Config::new("my_c_lib") .no_build_target(true) .always_configure(true) .build(); // This was the fix println!("cargo:rustc-flags=-l dylib=c++"); // The cmake crate outputs the static lib in the build subdir in the cargo $OUT_DIR, // which is a little different than their docs show. println!("cargo:rustc-link-search=native={}/build", dst.display()); println!("cargo:rustc-link-lib=static=my_c_lib"); } 

Please note that I have C / C ++ code as a submodule of git in native/ , and this project uses cmake.

This answer also helped.

0
source

Source: https://habr.com/ru/post/981330/


All Articles