Linking to a C++ library that has extern "C" functions
You need to dynamically link to libstdc++
to get the symbols your C++ code will need. You can instruct rustc
to do so 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 info on build scripts, see the Cargo guide.
This worked for me on macOS using the 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");
}
Note that I have the C/C++ code as a git submodule under native/
, and that project is using cmake.
This answer also helped.