我不知道如何将C库链接到Rust。以下是我所做的:
我的lib.rs文件包含
#[link(name = "test")]
extern {库是构建的,其名称为libtest.a。
我不知道该放在哪里。我尝试过几个地方,但是在执行cargo run时仍然存在这种类型的错误。
error: linking with `cc` failed: exit code: 1
//..
note: /usr/bin/ld: no se puede encontrar -ltest
note: /usr/bin/ld: no se puede encontrar -ltest
note: /usr/bin/ld:.......
//../usr/bin/ld: no se puede encontrar -ltest -> usr/bin/ld: cannot find -ltest的翻译
我不知道在哪里放置libtest.a以便/usr/bin/ld可以找到它。货运公司没有告诉我图书馆在项目中应该在哪里。
我的Cargo.toml包含
[dependencies.test]
path = "./src/test"
[dependencies]
bitflags = "0.7"
libc = "0.2"
[build-dependencies]
make-cmd = "0.1"在再次阅读文件的FFI部分之后,我想可能以前的错误消息是因为我在寻找一个共享库,所以我做了以下更改:
#[link(name = "test", kind = "static")]在这些更改之后,我仍然不知道如何指出库在哪里,但是消息现在告诉我如下:
error: could not find native static library `test`, perhaps an -L flag is missing?发布于 2017-05-07 04:33:41
我应该把静态库放在哪里?
你想去哪里都行。你必须告诉编译器在哪里能找到它。
首先,让我们创建一个静态库
$ cat hello.c
int square(int value) {
return value * value;
}
$ gcc -c -o hello.o hello.c
$ ar rcs libhello.a hello.o接下来,我们使用构建脚本将rustc-link-search的值设置为指向我放置库的目录:
fn main() {
println!("cargo:rustc-link-search=/Projects/stack-overflow/using-c-static/");
}我们现在可以使用库中的函数:
#[link(name = "hello")]
extern "C" {
fn square(val: i32) -> i32;
}
fn main() {
let r = unsafe { square(3) };
println!("3 squared is {}", r);
}这是基本的功能。您还可以使用构建脚本指定要链接的库,而不是在代码(rustc-link-lib)中链接它。我更喜欢这个,因为这两个配置是相邻的。
您还应该遵循命名约定并创建一个专门用于公开底层API的机箱。重要的是,这个机箱应该指定舱单密钥,以避免在链接时重复符号。
如果您的构建脚本需要更多信息,货通过环境变量传递许多参数。
发布于 2017-05-07 04:56:32
我刚刚找到了一个解决方案(两个),但我不知道这是否是最好的方法:
1-方法
build.rs文件
extern crate gcc;
fn main() {
println!("cargo:rustc-link-search=native=/home/path/to/rust/proyect/folder/contain/file.a");
println!("cargo:rustc-link-lib=static=test");
}Cargo.toml
//..
build = "build.rs"
//..2-方法
Cargo.toml
//..
rustc-link-search = ["./src/lib"]
rustc-link-lib = ["test"]
root = "/home/path/to/rust/proyect/"
//..["./src/lib"] -> place to lib.a refence to root
发布于 2021-05-11 11:32:56
如果您不想指定库的路径,并且您是在Linux上,您可以将它放在"usr/local/lib“中,然后在main.rs中这样说它的名称:
#[link(name = "theLibraryname", kind = "")]此外,还可以将任何头文件放置在“包含”文件夹中。
注意:库名没有lib .a 前缀和.a扩展名。
https://stackoverflow.com/questions/43826572
复制相似问题