如何使用C++/Qt/CMake项目构建Rust代码?

Dae*_*yth 31 c++ qt cmake rust

我有一个用CMake构建的现有C++/Qt 项目.我想开始添加Rust代码,我可以从主C++代码库中调用它.

什么是构建项目的正确方法?

目前的项目结构:

./CMakeLists.txt
./subproject-foo/CMakeLists.txt
./subproject-foo/src/...
./subproject-bar/CmakeLists.txt
./subproject-bar/src/...
./common/CMakeLists.txt
./common/src/...
Run Code Online (Sandbox Code Playgroud)

我想添加一个common-rust/...结构相似的目录.

我如何将其纳入项目?

Fra*_*ser 44

您可以使用该ExternalProject模块.它旨在允许构建外部依赖项 - 甚至是那些不使用CMake的依赖项.这是一篇关于使用它的有用文章.

所以说你有"common-rust"子目录,它的Cargo.toml包含:

[package]
name = "rust_example"
version = "0.1.0"

[lib]
name = "rust_example"
crate-type = ["staticlib"]
Run Code Online (Sandbox Code Playgroud)

add通过lib.rs 公开一个函数:

#[no_mangle]
pub extern fn add(lhs: u32, rhs: u32) -> u32 {
    lhs + rhs
}
Run Code Online (Sandbox Code Playgroud)

然后你的顶级CMakeLists.txt看起来像这样:

add_executable(Example cpp/main.cpp)

# Enable ExternalProject CMake module
include(ExternalProject)

# Set default ExternalProject root directory
set_directory_properties(PROPERTIES EP_PREFIX ${CMAKE_BINARY_DIR}/Rust)

# Add rust_example as a CMake target
ExternalProject_Add(
    rust_example
    DOWNLOAD_COMMAND ""
    CONFIGURE_COMMAND ""
    BUILD_COMMAND cargo build COMMAND cargo build --release
    BINARY_DIR "${CMAKE_SOURCE_DIR}/common-rust"
    INSTALL_COMMAND ""
    LOG_BUILD ON)

# Create dependency of Example on rust_example
add_dependencies(Example rust_example)

# Specify Example's link libraries
target_link_libraries(Example
    debug "${CMAKE_SOURCE_DIR}/common-rust/target/debug/librust_example.a"
    optimized "${CMAKE_SOURCE_DIR}/common-rust/target/release/librust_example.a"
    ws2_32 userenv advapi32)

set_target_properties(Example PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED ON)
Run Code Online (Sandbox Code Playgroud)

当您构建Rust目标时,staticlib它会输出应链接的其他库.我只是试图在Windows操作系统上,因此ws2_32,userenvadvapi32链接.这显然不是跨平台的,但是您可以轻松地处理(例如,将变量设置为适合于if..else块内每个平台的依赖项列表,并将其附加到target_link_libraries调用中).

另请注意,这取决于货物在路径中可用.

你现在应该好好去.文件"cpp/main.cpp"可能包含以下内容:

#include <cstdint>
#include <iostream>

extern "C" {
  uint32_t add(uint32_t lhs, uint32_t rhs);
}

int main() {
  std::cout << "1300 + 14 == " << add(1300, 14) << '\n';
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例项目的链接.


小智 8

现在有一个项目可以用来构建:Corrosion https://github.com/corrosion-rs/corrosion

所以你的 CMakeLists.txt 将只有这样:

# See the Corrosion README to find more ways to get Corrosion
find_package(Corrosion REQUIRED)

corrosion_import_crate(MANIFEST_PATH ${CMAKE_SOURCE_DIR}/common-rust)
Run Code Online (Sandbox Code Playgroud)