使用带有Rust的.c源文件

ele*_*ofw 10 rust

是否有标准的方法来包含.c源文件?

到目前为止,我一直在使用extern "C" { ... }公开函数,将.c编译为目标文件,运行rustc直到ld chokes与未定义的引用,并使用后面显示的参数error: linking with 'cc' failed with code 1; note: cc arguments: ...运行cc myobjfile.o ...

ele*_*ofw 7

编者注:此答案早于Rust 1.0,不再适用.

Luqman暗示了IRC; 在箱子文件中使用extern "C" { ... }with #[link_args="src/source.c"];对我有用.

  • 这很聪明.我以前从未见过有人这样做,也不一定会期望这种情况能够永远继续下去.这是有效的,因为Rust使用C编译器(当前总是gcc或clang)来驱动最终的链接步骤. (4认同)
  • (我希望它在不久的将来停止工作,此时) (3认同)

She*_*ter 5

在构建脚本中使用cc crate将 C 文件编译为静态库,然后将静态库链接到您的 Rust 程序:

Cargo.toml

[package]
name = "calling-c"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
edition = "2018"

[build-dependencies]
cc = "1.0.28"
Run Code Online (Sandbox Code Playgroud)

构建.rs

use cc;

fn main() {
    cc::Build::new()
        .file("src/example.c")
        .compile("foo");
}
Run Code Online (Sandbox Code Playgroud)

源代码/示例.c

[package]
name = "calling-c"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
edition = "2018"

[build-dependencies]
cc = "1.0.28"
Run Code Online (Sandbox Code Playgroud)

src/main.rs

extern "C" {
    fn testing(x: u8) -> u8;
}

fn main() {
    let a = unsafe { testing(21) };
    println!("a = {}", a);
}
Run Code Online (Sandbox Code Playgroud)