linux - 如何在不需要设置 LD_LIBRARY_PATH shell 变量的情况下键入 "cargo run"?

标签 linux rust

我构建了一个通过 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/

相关文章:

linux - Linux 中设备如何链接到驱动程序

rust - 如何将GBK编码的文件读入String?

rust - 是否可以返回或什么都不退?

rust - 如何从特征对象中获取对具体类型的引用?

rust - 如何在Rust中定义&mut [u8]

stream - 使用 nickel.rs 读取请求正文

linux - 如果字符出现在特定位置,则提取整行

linux - 在 Linux 中与 CashCode 账单接受器通信

linux - linux下如何取消目录的写权限?

mysql - 通过命令行更改表