11

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

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

4

2 回答 2

7

编者注:这个答案早于 Rust 1.0,不再适用。

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

于 2013-03-19T12:38:31.397 回答
5

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

货运.toml

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

[build-dependencies]
cc = "1.0.28"

构建.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);
}
于 2018-12-24T14:28:05.863 回答