使用 Rust 与 .c 源文件

11

有没有一种标准的方法可以包含 .c 源文件?

到目前为止,我已经使用 extern "C" { ... } 来公开这些函数,将 .c 编译为一个对象文件,运行 rustc 直到 ld 无法解决未定义的引用,并使用在 error: linking with 'cc' failed with code 1; note: cc arguments: ... 后显示的参数来运行 cc myobjfile.o ...

2个回答

7

编辑注意:此答案早于 Rust 1.0 版本,已不再适用。

Luqman在IRC上给了一个提示;在crate文件中使用extern "C" { ... }#[link_args="src/source.c"];对我有用。


4
聪明啊,我以前从未见过任何人这样做,也不一定期望这种方法会永远有效。这个方法之所以可行是因为 Rust 使用 C 编译器(目前始终为 gcc 或 clang)来驱动最后的链接步骤。 - brson
3
我预计它会在不久的将来停止工作,在这一点上。 - ember arlynx

6

使用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"

build.rs

use cc;

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

src/example.c

#include <stdint.h>

uint8_t testing(uint8_t i) {
  return i * 2;
}

src/main.rs

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

fn main() {
    let a = unsafe { testing(21) };
    println!("a = {}", a);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接