I am generating rust bindings for a c .so library using bindgen inside a build script
My build.rs file
let curr_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
println!(
"cargo:rustc-link-search=native={}",
curr_dir
);
println!("cargo:rustc-link-lib=dylib=my_library");
let bindings = bindgen::Builder::default()
.header("library_header.h")
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
bindings
.write_to_file(out_path.join("src/bindings.rs"))
.expect("Couldn't write bindings!");
The bindings are generated correctly but when I am trying to use the library by running cargo test I am getting error
/target/debug/deps/rust-binary: error while loading shared libraries: my_library.so: cannot open shared object file: No such file or directory
I have created an env varible also export LD_LIBRARY_PATH= /path/to/my_library/ as suggested by @jofas
Weirdly when I place my .so file inside /usr/lib I am able to access the library functions. I am new to rust and ffi and I know I am doing something stupid. Can someone please help
to tell Cargo (which then tells rustc) where to look for the library. Because you are using a dynamically linked .so lib, you need to tell Cargo, or more precisely the linker, where to find the library at run time as well. One way is to put the library in a path where the linker can find it, as you already discovered. But you should also be able to use LD_LIBRARY_PATH or pass -L native=path/to/your/lib to rustc via the build.rustflags of your Cargo configuration file.