ZhangHanDong / tao-of-rust-codes

《Rust编程之道》随书源码
https://ruststudy.github.io/tao_of_rust_docs/tao_of_rust/
MIT License
1.19k stars 172 forks source link

[第十三章] 因缺少LD_LIBRATY_PATH变量导致c程序无法运行 #289

Open huangjj27 opened 4 years ago

huangjj27 commented 4 years ago

在 WSL/Linux 环境下 根据页面 第518 - 520页的代码示例,对在c程序中 调用 rust 编译好的 libcallrust.so 文件时出现了如下报错:

./c_src/main: error while loading shared libraries: libcallrust.so: cannot open shared object file: No such file or directory
makefile:5: recipe for target 'run' failed
make: *** [run] Error 127

经查明。在makefile 运行中指定链接目录变量 LD_LIBRARY_PATH可以顺利运行:

$ make run
/home/huangjj27/.cargo/bin/cargo clean
rm -f ./c_src/main
/home/huangjj27/.cargo/bin/cargo build
   Compiling libc v0.2.69
   Compiling callrust v0.1.0 (/mnt/c/Users/huangjj27/Documents/codes/callrust)
warning: unused import: `libc`
 --> src/lib.rs:1:5
  |
1 | use libc;
  |     ^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

    Finished dev [unoptimized + debuginfo] target(s) in 5.83s
/usr/bin/gcc -o ./c_src/main ./c_src/main.c -I./src -L./target/debug -lcallrust
LD_LIBRARY_PATH=./target/debug ./c_src/main
Hello from rust

代码错误

# makefile

GCC_BIN ?= $(shell which gcc)
CARGO_BIN ?= $(shell which cargo)

run: clean build
    LD_LIBRARY_PATH=./target/debug ./c_src/main  # 在运行时应该添加链接目录变量!

clean:
    $(CARGO_BIN) clean
    rm -f ./c_src/main

build:
    $(CARGO_BIN) build
    $(GCC_BIN) -o ./c_src/main ./c_src/main.c -I./src -L./target/debug -lcallrust

Rust版本

$ rustc -V
rustc 1.43.0 (4fb7144ed 2020-04-20)
huangjj27 commented 4 years ago

另外,可以考虑对该示例新增静态链接的示例:

gcc -o ./c_src/main ./c_src/main.c ./target/debug/libcallrust.a
ZhangHanDong commented 4 years ago

@huangjj27 感谢反馈。 在第二版中考虑增加Linux下的说明。