使用 prefer-dynamic 时无法执行 hello world 项目

Unable to execute a hello world project when using prefer-dynamic

我正在一个非常简单的项目上使用 Rust 的编译选项,你好世界:

fn main() {
    println!("Hello, world!");
}

我正在用这一行进行编译,prefer-dynamic 是唯一值得注意的选项:

rustc main.rs -o ./build/rci -C prefer-dynamic

它工作正常,直到我做了一些更改,然后就没有了。现在,如果我尝试完全按照上面的方式编译代码,我会得到以下输出:

./build/rci: error while loading shared libraries: libstd-2ddb28df747fcb8c.so: cannot open shared object file: No such file or directory

ldd 的输出是:

linux-vdso.so.1 =>  (0x00007ffd321a4000)
libstd-2ddb28df747fcb8c.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f52eaef3000)
/lib64/ld-linux-x86-64.so.2 (0x000055f0f6251000)

这是 Ubuntu 17.04 和 Rust 1.15.1。

您应该检查您的术语;编程时,单词表示特定的事物。您可以 编译 您的代码,正如调用 Rust 编译器 (a.k.a. rustc) 没有任何错误这一事实所示。

您的问题发生在执行程序时。这些是非常不同的概念,它将帮助您很好地理解它们之间的区别。

"problem" 是您...正在使用动态链接,正如您所要求的那样。这 不是 Rust 问题,只是一个一般的编程问题。我敢肯定有很多 SO 问题,例如 Linux error while loading shared libraries: cannot open shared object file: No such file or directory or one of the 500 other questions with that error message 可以为您提供更多信息。

您正在动态链接 Rust 标准库,但您的系统不知道该库,因为它没有安装在您的系统知道的位置。很可能,您是通过 rustup 安装的,所以该库位于您的主目录中。比如我的在/home/ubuntu/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/libstd-f4594d3e53dcb114.so.

您会发现许多 种可能的解决方案。最简单的演示是使用 LD_LIBRARY_PATH 变量:

$ ./example
./example: error while loading shared libraries: libstd-f4594d3e53dcb114.so: cannot open shared object file: No such file or directory
$ LD_LIBRARY_PATH=/home/ubuntu/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/ ./example
Hello, world!

您也可以查看


为了帮助发现这一点,您可以制作 Rust print out the linker invocation it uses:

$ rustc +nightly -Cprefer-dynamic -Z print-link-args hello.rs
"cc" "-m64" "-L" "/Users/shep/.rustup/toolchains/nightly-x86_64-apple-darwin/lib/rustlib/x86_64-apple-darwin/lib" "hello.hello0.rcgu.o" "hello.hello1.rcgu.o" "hello.hello2.rcgu.o" "hello.hello3.rcgu.o" "hello.hello4.rcgu.o" "hello.hello5.rcgu.o" "-o" "hello" "hello.crate.allocator.rcgu.o" "-Wl,-dead_strip" "-nodefaultlibs" "-L" "/Users/shep/.rustup/toolchains/nightly-x86_64-apple-darwin/lib/rustlib/x86_64-apple-darwin/lib" "-L" "/Users/shep/.rustup/toolchains/nightly-x86_64-apple-darwin/lib/rustlib/x86_64-apple-darwin/lib" "-l" "std-834fbefe8dbe98b5" "/Users/shep/.rustup/toolchains/nightly-x86_64-apple-darwin/lib/rustlib/x86_64-apple-darwin/lib/libcompiler_builtins-b4312e2f1496a4e4.rlib" "-l" "System" "-l" "resolv" "-l" "pthread" "-l" "c" "-l" "m"

可以看到链接器路径中添加了"-L" "/Users/shep/.rustup/toolchains/nightly-x86_64-apple-darwin/lib/rustlib/x86_64-apple-darwin/lib",然后"-l" "std-834fbefe8dbe98b5"链接了标准库