我构建了一个 Rust 程序,通过 C 接口调用 C++ 函数。为了执行该程序,我必须运行:
export LD_LIBRARY_PATH=<path to shared c lib>
Run Code Online (Sandbox Code Playgroud)
或者我收到错误:
error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下命令在构建脚本中设置变量std::process::Command
Command::new("sh").arg("export").arg("LD_LIBRARY_PATH=<path to shared c lib>");
Run Code Online (Sandbox Code Playgroud)
尽管该命令执行时没有错误,但该变量未设置。如何在程序执行时设置该变量?
更具体地说,我只想输入以下内容:
Command::new("sh").arg("export").arg("LD_LIBRARY_PATH=<path to shared c lib>");
Run Code Online (Sandbox Code Playgroud)
代替
cargo run
Run Code Online (Sandbox Code Playgroud)
到目前为止我的代码:
主程序.rs
/*---compile all with---
g++ -c -fpic foo.cpp
gcc -c -fpic test.c
g++ -shared foo.o test.o -o libtest.so
in order to execute we have to set the variable
export LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/$LD_LIBARY_PATH
*/
//pub extern crate c_interface;
pub extern crate libc;
use libc::{c_int};
#[link(name = "test")]
extern "C" {
fn hello_world () -> c_int;
}
fn main() {
let x;
unsafe {
x = hello_world();
}
println!("x is: {}", x);
}
Run Code Online (Sandbox Code Playgroud)
测试.c
export LD_LIBRARY_PATH=<path to shared c lib>
cargo run
Run Code Online (Sandbox Code Playgroud)
foo.cpp
/*---compile all with---
g++ -c -fpic foo.cpp
gcc -c -fpic test.c
g++ -shared foo.o test.o -o libtest.so
in order to execute we have to set the variable
export LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/$LD_LIBARY_PATH
*/
//pub extern crate c_interface;
pub extern crate libc;
use libc::{c_int};
#[link(name = "test")]
extern "C" {
fn hello_world () -> c_int;
}
fn main() {
let x;
unsafe {
x = hello_world();
}
println!("x is: {}", x);
}
Run Code Online (Sandbox Code Playgroud)
foo.h
#include "foo.h"
int hello_world () {
int a = foo();
return a;
}
Run Code Online (Sandbox Code Playgroud)
构建.rs
fn main () {
println!(r"cargo:rustc-link-search=native=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut");
}
Run Code Online (Sandbox Code Playgroud)
我已经看到如何在 Rust 中指定链接器路径?这并不能解决我的问题。
将以下行添加到 build.rs:
println!("cargo:rustc-env=LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/");
Run Code Online (Sandbox Code Playgroud)
这仅适用于cargo run然后cargo build执行输出。环境变量不会保存到二进制文件中。