[英]How can I type “cargo run” without needing to set the LD_LIBRARY_PATH shell variable?
我構建了一個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
到目前為止,我的代碼:
主
/*---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);
}
測試
#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
構建器
fn main () {
println!(r"cargo:rustc-link-search=native=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut");
}
我已經看到了如何在Rust中指定鏈接器路徑? 這不是我的問題的解決方案。
將以下行添加到build.rs中:
println!("cargo:rustc-env=LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/");
這僅適用於cargo run
,不適用於cargo build
,然后執行輸出。 環境變量不會保存到二進制文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.