我构建了一个Rust程序,该程序通过C接口调用C ++函数。为了执行程序,我必须运行:
export LD_LIBRARY_PATH=<path to shared c lib>
或者我得到一个错误:
error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
我尝试使用std::process::Command
Command::new("sh").arg("export").arg("LD_LIBRARY_PATH=<path to shared c lib>");
尽管命令执行没有错误,但未设置变量。在执行程序时如何从程序中设置变量?
更具体地说,我只想输入:
cargo run
代替
export LD_LIBRARY_PATH=<path to shared c lib>
cargo run
到目前为止,我的代码:
main.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);
}
test.c
#include "foo.h"
int hello_world () {
int a = foo();
return a;
}
foo.cpp
#include <iostream>
#include "foo.h"
using namespace std;
int foo() {
cout << "Hello, World!" << endl;
return 0;
}
foo.h
#ifdef __cplusplus
extern "C" {
#endif
int foo();
#ifdef __cplusplus
}
#endif
build.rs
fn main () {
println!(r"cargo:rustc-link-search=native=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut");
}
我见过How do I specify the linker path in Rust?,但这并不是解决我的问题的方法。
答案 0 :(得分:-1)
将以下行添加到build.rs:
println!("cargo:rustc-env=LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/");
这仅适用于cargo run
,不适用于cargo build
,然后执行输出。环境变量不会保存到二进制文件中。