简体   繁体   English

如何在不设置LD_LIBRARY_PATH shell变量的情况下键入“货物运行”?

[英]How can I type “cargo run” without needing to set the LD_LIBRARY_PATH shell variable?

I build a Rust program that calls a C++ function via a C interface. 我构建了一个Rust程序,该程序通过C接口调用C ++函数。 In order to execute the program, I have to run: 为了执行程序,我必须运行:

export LD_LIBRARY_PATH=<path to shared c lib>

or I get an error: 或我得到一个错误:

error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory

I tried to set the variable in a build script using std::process::Command 我试图使用std::process::Command在构建脚本中设置变量

Command::new("sh").arg("export").arg("LD_LIBRARY_PATH=<path to shared c lib>");

Although the command executes without an error, the variable is not set. 尽管命令执行没有错误,但未设置变量。 How can I set the variable from my program while it is being executed? 在执行程序时如何从程序中设置变量?

To be more concrete, I want to type only this: 更具体地说,我只想输入以下内容:

cargo run

instead of 代替

export LD_LIBRARY_PATH=<path to shared c lib>
cargo run

My code so far: 到目前为止,我的代码:

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 foo.cpp

#include <iostream>
#include "foo.h"

using namespace std;

int foo() {
    cout << "Hello, World!" << endl;
    return 0;
}

foo.h 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");
}

I have seen How do I specify the linker path in Rust? 我已经看到了如何在Rust中指定链接器路径? and it is not a solution to my problem. 这不是我的问题的解决方案。

Add the following line to build.rs: 将以下行添加到build.rs中:

println!("cargo:rustc-env=LD_LIBRARY_PATH=/home/jan/Uni/Bachelorarbeit/Programme/Rust_Cpp_crossover_erneut/");

This only works with cargo run and not with cargo build and then executing the output. 这仅适用于cargo run ,不适用于cargo build ,然后执行输出。 The environment variable does not get saved into the binary. 环境变量不会保存到二进制文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM