Using .c source files with Rust

前端 未结 2 1147
-上瘾入骨i
-上瘾入骨i 2020-12-06 11:33

Is there a standard way to include .c source files?

So far I\'ve been using extern \"C\" { ... } to expose the functions, compiling .c to an object file

相关标签:
2条回答
  • 2020-12-06 12:02

    Use the cc crate in a build script to compile the C files into a static library and then link the static library to your Rust program:

    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);
    }
    
    0 讨论(0)
  • 2020-12-06 12:07

    Editor's note: This answer predates Rust 1.0 and is no longer applicable.

    Luqman gave a hint on IRC; using extern "C" { ... } with #[link_args="src/source.c"]; in the crate file works for me.

    0 讨论(0)
提交回复
热议问题