How to Use cc and cmake Crates for Building C Code

Use the cc crate for simple C compilation and the cmake crate for complex C/C++ builds within Rust projects.

Use the cc crate to compile C code directly within your Rust build script, and use the cmake crate to invoke CMake for complex C/C++ projects. Add the crates to your Cargo.toml dependencies and call their builder methods in build.rs to handle compilation flags and linking automatically.

// build.rs
fn main() {
    // Compile C code using cc crate
    cc::Build::new()
        .file("src/native.c")
        .flag("-O2")
        .compile("native-lib");

    // Build CMake project using cmake crate
    cmake::Config::new("vendor/my-c-lib")
        .define("BUILD_SHARED_LIBS", "OFF")
        .build();
}