gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:45:04 25 4
gpt4 key购买 nike

我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com