rust - 如何在 Rust 中指定链接器路径?

标签 rust static-linking dynamic-linking rust-cargo

我正在尝试将 Rust 程序与 libsoundio 链接起来.我使用的是 Windows,并且可以下载 GCC 二进制文件。如果我将它放在与我的项目相同的文件夹中,我可以像这样链接它:

#[link(name = ":libsoundio-1.1.0/i686/libsoundio.a")]
#[link(name = "ole32")]
extern {
    fn soundio_version_string() -> *const c_char;
}

但我真的想指定#[link(name = "libsoundio")]甚至#[link(name = "soundio")],然后在其他地方提供链接器路径。

我在哪里可以指定该路径?

我尝试了 rustc-link-search 建议如下:

#[link(name = "libsoundio")]
#[link(name = "ole32")]
extern {
    fn soundio_version_string() -> *const c_char;
}

.cargo/config 中:

[target.i686-pc-windows-gnu.libsoundio]
rustc-link-search = ["libsoundio-1.1.0/i686"]
rustc-link-lib = ["libsoundio.a"]

[target.x86_64-pc-windows-gnu.libsoundio]
rustc-link-search = ["libsoundio-1.1.0/x86_64"]
rustc-link-lib = ["libsoundio.a"]

但它仍然只将 "-l""libsoundio" 传递给 gcc,并以相同的 ld: cannot find -llibsoundio 失败。我错过了一些非常明显的东西吗?文档似乎表明这应该有效。

最佳答案

documentation for a build script 中所述:

All the lines printed to stdout by a build script [... starting] with cargo: is interpreted directly by Cargo [...] rustc-link-search indicates the specified value should be passed to the compiler as a -L flag.

在您的 Cargo.toml 中:

[package]
name = "link-example"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
build = "build.rs"

还有你的build.rs:

fn main() {
    println!(r"cargo:rustc-link-search=C:\Rust\linka\libsoundio-1.1.0\i686");
}

请注意,您的构建脚本可以使用 Rust 的所有功能,并且可以根据目标平台(例如 32 位和 64 位)输出不同的值。

最后,你的代码:

extern crate libc;

use libc::c_char;
use std::ffi::CStr;

#[link(name = "soundio")]
extern {
    fn soundio_version_string() -> *const c_char;
}

fn main() {
    let v = unsafe { CStr::from_ptr(soundio_version_string()) };
    println!("{:?}", v);
}

证据就在布丁里:

$ cargo run
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target\debug\linka.exe`
"1.0.3"

理想情况下,您将创建一个 soundio-sys 包,使用 the convention for *-sys packages .它只是有一个链接到适当库并公开 C 方法的构建脚本。它将使用 Cargo links key唯一标识 native 库并防止多次链接到它。然后其他库可以包含这个新的 crate,而不用担心那些链接细节。

关于rust - 如何在 Rust 中指定链接器路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40833078/

相关文章:

rust - 为什么对 Regex::find 的结果进行匹配会提示期望结构 regex::Match 但找到元组?

java - -Djava.library.path 没有链接 .so 库

c - 如何在 C 中创建模块

c - 了解动态加载库中的地址

struct - rust:如何使用引用外部值的回调编写 `impl`

build - 如何从构建脚本 (build.rs) 访问当前的 cargo 配置文件(调试/发布,...)

rust - 在 Rust 中多次使用具有相同变量名的 let 关键字

program-entry-point - 链接器使用 Boost.Test 选择 "wrong"main

编译自定义 malloc

c - C 中是否存在可以分配/强制转换为限制性更强的原型(prototype)的通用函数指针之类的东西?