Rust 不能 link 绑定到 C 库

Rust can't link bindings to C library

我关注了rust-bindgen tutorial to make bindings for the scrypt C library。由于链接错误,我无法 运行 我的测试:

/home/user/project/rust-scrypt/src/lib.rs:32: undefined reference to `crypto_scrypt'
      collect2: error: ld returned 1 exit status

和我的测试:

include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
// ...
// ...
#[test]
fn test_script() {
  let mut kdf_salt = to_bytes("fd4acb81182a2c8fa959d180967b374277f2ccf2f7f401cb08d042cc785464b4");
    let passwd = "1234567890";
    let mut buf = [0u8; 32];

    unsafe {
        crypto_scrypt(passwd.as_ptr(), passwd.len(), kdf_salt.as_mut_ptr(), kdf_salt.len(),
                      2, 8, 1, buf.as_mut_ptr(), 32);
    }

    println!(">> DEBUG: {:?}", buf);
    // "52a5dacfcf80e5111d2c7fbed177113a1b48a882b066a017f2c856086680fac7");
}

绑定已生成并存在于 bindings.rs 中。我不知道为什么链接器会抛出错误。

这是我的builds.rs

extern crate bindgen;

use std::env;
use std::path::PathBuf;

fn main() {
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    let bindings = bindgen::Builder::default()
        .no_unstable_rust()
        .header("wrapper.h")
        .generate()
        .expect("Unable to generate bindings");

    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}

还有我的Cargo.toml

[package]
name = "rust-scrypt"
version = "0.0.1"
build = "build.rs"

[build-dependencies]
bindgen = "0.23"

请重新熟悉the "Building some native code" case study。具体来说,你已经告诉 Rust 库的接口是什么,但是你还没有告诉编译器代码在哪里。这就是您收到的错误信息:"I can't find the implementation of crypto_scrypt"

您需要将库添加到 linker 路径 并指示它被link编辑。

根据 linked 案例研究,您的构建脚本可以通知编译器库在哪里以及 link 反对什么:

println!("cargo:rustc-link-search=native={}", path_to_library);
println!("cargo:rustc-link-lib=static=hello"); // the name of the library

拜托,拜托,拜托阅读关于*-sys packages which documents the best practices for this type of integration. Namely, your Cargo.toml is missing the links key的部分,如果有人尝试,这将导致问题到这个图书馆多次 link。

--

请注意,已经有 crates that purport to provide scrypt