Rust/C/C++ 混合构建 - Cmake集成Cargo编译动态库

Cmake是一个强大的多语言编译工具,其内置模块提供了强大的扩展能力。

Rust官方的构建工具是Cargo,其提供了依赖下载,上传和编译等多项功能,极大的便利了Rust项目的开发。

目前C++多数用Cmake构建,如果是Rust集成cmake构建c++动态库,可以用Cargo构建脚本集成cmake-rs构建。

如果要调用Cargo构建Rust编译的动态库,并且通过cmake作为构建工具统一调度,目前主流方案是使用Cmake内置的add_custom_target模块调用Cargo构建。

Playground

1、cargo new rust-lib ---lib 创建rust 项目,并在Cargo.toml中指定类型为cdylib

toml 复制代码
[package]
name = "rust_lib"
version = "0.1.0"
edition = "2021"

[dependencies]

[lib]
crate-type = ["cdylib"]

2、在 src/lib.rs 创建greet_from_rust动态库函数

rust 复制代码
#[no_mangle]
pub extern "C" fn greet_from_rust() {
    println!("Hello, greeting!")
}

3、创建call_rust.c,内容如下

c 复制代码
extern void greet_from_rust();

int main(void) {
    greet_from_rust();
    return 0;
}

4、编写Cmake构建规则,创建CMakeLists.txt, 其内容如下

复制代码
cmake_minimum_required(VERSION 3.22)
project(call_rust)

set(ARGS --target-dir ${CMAKE_BINARY_DIR}/target)

if (CMAKE_BUILD_TYPE STREQUAL "Release")
    message(STATUS "[RUST] Detected release build")
    set(build_profile "release")
    set(ARGS ${ARGS} --release)
else()
    message(STATUS "[RUST] Using default debug build")
    set(build_profile "debug")
endif()

add_custom_target(
    cargo_build ALL
    COMMAND 
        ${CMAKE_COMMAND} -E env 
        cargo build ${ARGS}
    DEPENDS src/lib.rs
)

add_executable(call_rust call_rust.c)
add_library(rust_lib SHARED IMPORTED)
set_property(TARGET rust_lib PROPERTY IMPORTED_LOCATION "${CMAKE_BINARY_DIR}/target/${build_profile}/librust_lib.so")
target_link_libraries(call_rust PUBLIC rust_lib)总结

add_custom_target调用Cargo将src/lib.rs 编译成动态库,为了方便将Cargo的构建目录指定在当前项目下。

add_libraryset_property 将生成的动态库绑定到rust_lib 这个target上,最后将动态库rust_lib通过

target_link_libraries 链接到call_rust二进制target上

Cmake构建配置完成,我们可以通过

cmake -DCMAKE_BUILD_TYPE:STRING=Release . cmake -DCMAKE_BUILD_TYPE:STRING=Debug .

这两个命令切换构建选项,这也对应了Cargo构建的---release选项,然后通过

cmake ---build . 构建当前项目, 输出

shell 复制代码
$ cmake  -DCMAKE_BUILD_TYPE:STRING=Release . && cmake --build . && ./call_rust
-- [RUST] Detected release build
-- Configuring done
-- Generating done
-- Build files have been written to: /root/workspace/build-tool-examples/rust_lib
Compiling rust_lib v0.1.0 (/root/workspace/build-tool-examples/rust_lib)
Finished release profile [optimized] target(s) in 0.44s
[  0%] Built target cargo_build
Consolidate compiler generated dependencies of target call_rust
[ 50%] Linking C executable call_rust
[100%] Built target call_rust
Hello, greeting!
相关推荐
LengineerC3 小时前
Rust仿node事件总线的简单实现
设计模式·rust
r***d8655 小时前
Rust宏编程指南
开发语言·后端·rust
星释5 小时前
Rust 练习册 80:Grains与位运算
大数据·算法·rust
wei_shuo6 小时前
zoxide 开源鸿蒙 PC 生态适配实战:Rust 交叉编译与 HNP 打包完整指南
rust·开源鸿蒙·zoxide
大鱼七成饱18 小时前
Rust进阶必备:thiserror用法全面解析
rust
Amos_Web19 小时前
Rust实战(四):数据持久化、告警配置与Web API —— 构建监控系统的功能闭环
前端·后端·rust
联系QQ:48773927820 小时前
Bayes-CNN-LSTM、Bayes-CNN-BiLSTM、Bayes-CNN-GRU、B...
rust
空白诗1 天前
tokei 在鸿蒙PC上的构建与适配
后端·华为·rust·harmonyos
疏狂难除1 天前
尝试rust与python的混合编程(一)
开发语言·后端·python·rust
H***99761 天前
Rust在WebAssembly中的使用
开发语言·rust·wasm