How to link Cmake project in CXX?

I did this in cxx:

fn main() {
	cxx_build::bridge("src/main.rs")
        .file("src/something.cc")
        .flag_if_supported("-std=c++17")
        .compile("my_demo");
}

I want to link something.cc with another C++ library, but still run everything on Rust. I thus want to call C++ code, from Rust, and still have it compiled and linked using Cargo. All the projects I find are the inverse: compiling rust from Cmake and using on C++.

So, how do I compile a cmake project from build.rs and link to something.cc?

Well, as far as I can tell, this should work as-is, in the sense that it should already invoke the compiler and the linker properly, that's the very purpose of cxx_build. This allows you to call the C++ code from your main.rs if you create the appropriate declarations in Rust.

Did you look at the complete, runnable demo?

I made the demo work, but my code needs a really large C++ library that is only buildable by cmake. So I need to link something.cc with this lib

In that case, build the library using CMake, and specify an install directory that is accessible by the Rust build. Then, emit cargo:rustc-link-lib commands from the build script, see here.

You can also use the cmake crate for running cmake. Here is an example from the docs:

use cmake::Config;

let dst = Config::new("libfoo")
                 .define("FOO", "BAR")
                 .cflag("-foo")
                 .build();
println!("cargo:rustc-link-search=native={}", dst.display());
println!("cargo:rustc-link-lib=static=foo");
1 Like

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.