在 Rust 中指定 FFI 库的链接路径有哪些不同的方法?
What are the different ways of specifying the linking path to FFI libraries in Rust?
以下面的代码为例:
extern crate libc;
#[link(name = "adder")]
extern {
fn double_input(input: libc::c_int) -> libc::c_int;
}
fn main() {
let input = 4;
let output = unsafe { double_input(input) };
println!("{} * 2 = {}", input, output);
}
#[link(name = "adder")]
是否应该包含 .o / a / .h 文件的相对路径?比如应该是#[link(name = "../adderlib/adder")]
?还有另一种方法可以告诉编译器 adder
在哪里吗?
如果您需要控制库的查找方式或链接到您的 Rust 代码的方式,您应该通过 build script。
第一个问题的答案是肯定的!如果您的 lib 文件是 libfoo.o
,那么在您的代码中 #[link(name = "foo")
就足够了。 official documentation.
中有更多详细信息
会相对于当前工作路径下的lib文件和系统lib路径。 (我在任何文档中都找不到这个,但我曾经成功地做到了)。您可以使用 rustc -l XX -L XX
指定路径。使用带有 build script 的 Cargo 是更好的方法。
以下面的代码为例:
extern crate libc;
#[link(name = "adder")]
extern {
fn double_input(input: libc::c_int) -> libc::c_int;
}
fn main() {
let input = 4;
let output = unsafe { double_input(input) };
println!("{} * 2 = {}", input, output);
}
#[link(name = "adder")]
是否应该包含 .o / a / .h 文件的相对路径?比如应该是#[link(name = "../adderlib/adder")]
?还有另一种方法可以告诉编译器 adder
在哪里吗?
如果您需要控制库的查找方式或链接到您的 Rust 代码的方式,您应该通过 build script。
第一个问题的答案是肯定的!如果您的 lib 文件是 libfoo.o
,那么在您的代码中 #[link(name = "foo")
就足够了。 official documentation.
会相对于当前工作路径下的lib文件和系统lib路径。 (我在任何文档中都找不到这个,但我曾经成功地做到了)。您可以使用 rustc -l XX -L XX
指定路径。使用带有 build script 的 Cargo 是更好的方法。