我构建了一个通过 C 接口(interface)调用 C++ 函数的 Rust 程序。为了执行程序,我必须运行:
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
到目前为止我的代码:
主要.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);
}
测试.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
构建.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?这不是我的问题的解决方案。
最佳答案
将以下行添加到 build.rs:
println!("cargo:rustc-env=LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/");
这仅适用于 cargo run
而不适用于 cargo build
然后执行输出。环境变量不会保存到二进制文件中。
关于linux - 如何在不需要设置 LD_LIBRARY_PATH shell 变量的情况下键入 "cargo run"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51796417/