Search code examples
crustffi

Where do I specify the filename to link to in FFI for Rust?


I'm experimenting with FFI on Rust, but I can't find how you tell cargo run where to find your C code, after 2 hours of searching.

I know there's an FFI chapter in the Rust book, but it doesn't state what should I pass to cargo run so that it knows that my C file is located at ./c/main.c.

Rust code:

#[link(name = "main")]
extern {
    fn a() -> u8;
}

fn main() {
    println!("{}", unsafe {
        a()
    });
}

C code:

char a() {
    return 'A';
}

Do I need to compile the C code to an .o file so that Rust can detect it? Where should I put it if I need to do so? I am on Windows.

I also tried adding a build script that prints cargo:rustc-link-search=./ but that didn't fix it.

The error I get is:

ld: cannot find -lmain

Solution

  • Your Cargo.toml should look like:

    [build-dependencies]
    cc = "1.0.32"
    

    You should also have a build.rs located in the same folder as Cargo.toml:

    extern crate cc;
    
    fn main() {
        cc::Build::new()
            .file("src/main.c") //here I specify that main.c is in src folder, you can change the location likewise
            .compile("libmain.a");
    }
    
    

    Finally, main.rs has:

    extern "C" {
        fn a() -> u8;
    }
    
    fn main() {
        println!("{}", unsafe { a() });
    }
    

    After this, running cargo run will compile the C code and link it as a library, you might find these examples useful.