[rust-dev] Using CMake with Rust

SiegeLord slabode at aim.com
Wed Jan 1 20:26:42 PST 2014


(Posting this here as I think it might be useful for some but I don't 
feel like getting a Reddit account and there's no rust-announce).

I've been experimenting with building Rust crates using some established 
build systems, focusing on SCons and CMake due to their popularity. 
Neither turned out to be a perfect fit for Rust, but CMake was 
marginally less bad so I chose it in the end. To that end I created some 
CMake modules that make that integration be as painless as possible. 
Here's what a minimal CMakeLists.txt would look like for a single 
library crate project:

~~~
cmake_minimum_required(VERSION 2.8)
project(testlib NONE)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
find_package(rustc)
find_package(rustdoc)
include(Rust)

set(RUSTC_FLAGS "-L${CMAKE_BINARY_DIR}/lib")

rust_crate_auto(src/lib.rs TARGET_NAME TESTLIB)

add_custom_target(library_target
                   ALL
                   DEPENDS ${TESTLIB_FULL_TARGET})

install(FILES ${TESTLIB_ARTIFACTS}
         DESTINATION lib)
~~~

And then you'd do the usual out-of-source build. It will reconfigure the 
build system if any of the files referenced by src/lib.rs (as reported 
by rustc --dep-info) get changed. A more complete example that shows 
building several inter-dependent crates, documentation and tests can be 
seen here: https://github.com/SiegeLord/RustCMake . The modules for this 
to work are also found there.

Caveats: CMake doesn't know what Rust is, so it has to reconfigure the 
entire build system whenever you change any of the source files needed 
for *ANY* crate in your project (it doesn't need to do that with C/C++ 
because it has an internal dependency scanner). This won't be a big deal 
in small projects, and I find the convenience of using CMake to be worth 
it, but it does suggest that CMake is not the ultimate solution to 
building Rust projects.

-SL


More information about the Rust-dev mailing list