有没有一种标准的方法可以包含 .c 源文件?
到目前为止,我已经使用 extern "C" { ... }
来公开这些函数,将 .c 编译为一个对象文件,运行 rustc 直到 ld 无法解决未定义的引用,并使用在 error: linking with 'cc' failed with code 1; note: cc arguments: ...
后显示的参数来运行 cc myobjfile.o ...
有没有一种标准的方法可以包含 .c 源文件?
到目前为止,我已经使用 extern "C" { ... }
来公开这些函数,将 .c 编译为一个对象文件,运行 rustc 直到 ld 无法解决未定义的引用,并使用在 error: linking with 'cc' failed with code 1; note: cc arguments: ...
后显示的参数来运行 cc myobjfile.o ...
编辑注意:此答案早于 Rust 1.0 版本,已不再适用。
Luqman在IRC上给了一个提示;在crate文件中使用extern "C" { ... }
和#[link_args="src/source.c"];
对我有用。
使用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);
}