Crates.io | cmake-preset |
lib.rs | cmake-preset |
version | 0.1.0 |
created_at | 2025-09-18 07:26:02.932479+00 |
updated_at | 2025-09-18 07:26:02.932479+00 |
description | A Rust library for building C++ code in Rust projects using CMake Presets, providing type-safe builder patterns and automatic Cargo integration. |
homepage | |
repository | https://github.com/mengyou1024/cmake-preset.git |
max_upload_size | |
id | 1844338 |
size | 11,702 |
A Rust library for building C++ code using CMake Presets in Rust projects.
This library provides a simple and type-safe way to integrate CMake builds into Rust projects. It uses the builder pattern with type states to ensure all required steps are performed in the correct order when building C++ code with CMake Presets.
Add this to your Cargo.toml
:
[build-dependencies]
cmake-preset = { version = "0.1.0" }
Create a build.rs
file in your project:
use cmake_preset::*;
fn main() {
if cfg!(target_os = "windows") {
CMakePresetBuilder::new()
.set_project_dir("cpp-lib")
.set_config_preset("msvc-x64-static-mt-rel")
.set_library_name("cpp-lib")
.config()
.build();
} else if cfg!(target_os = "linux") {
CMakePresetBuilder::new()
.set_project_dir("cpp-lib")
.set_config_preset("gcc-x64-static-rel")
.set_library_name("cpp-lib")
.config()
.build();
// Link libstdc++
println!("cargo:rustc-link-lib=static=stdc++");
}
}
Then you can link to and use your C++ functions in Rust:
unsafe extern "C" {
#[link_name = "Add"]
unsafe fn add(a: i32, b: i32) -> i32;
#[link_name = "Hello"]
unsafe fn hello();
}
fn main() {
println!("{}", unsafe { add(1, 2) });
unsafe { hello() };
}
The library uses Rust's type system to enforce correct usage at compile time:
StatusSetProjectDir
- Initial state, requires setting the project directoryStatusSetConfigPreset
- Requires setting the CMake preset nameStatusSetLibraryName
- Requires setting the static library name of generatedStatusConfig
- Ready to run CMake configurationStatusBuild
- Ready to build the projectThis ensures that all required steps are performed in the correct order.
See the example
directory for a complete example of how to use this library to build and link a C++ library in a Rust project.