是否有标准的方法来包含.c源文件?
到目前为止,我一直在使用extern "C" { ... }公开函数,将.c编译为目标文件,运行rustc直到ld chokes与未定义的引用,并使用后面显示的参数error: linking with 'cc' failed with code 1; note: cc arguments: ...运行cc myobjfile.o ...
编者注:此答案早于Rust 1.0,不再适用.
Luqman暗示了IRC; 在箱子文件中使用extern "C" { ... }with #[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"
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)
| 归档时间: |
|
| 查看次数: |
1142 次 |
| 最近记录: |