linker: Better support alternative static library naming on MSVC

Previously `libname.a` naming was supported as a fallback when producing rlibs, but not when producing executables or dynamic libraries
This commit is contained in:
Vadim Petrochenkov 2024-08-22 01:56:20 +03:00
parent a1c36c6ae9
commit 05bd36de50
4 changed files with 28 additions and 4 deletions

View File

@ -7,7 +7,7 @@ use std::{env, iter, mem, str};
use cc::windows_registry;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_metadata::find_native_static_library;
use rustc_metadata::{find_native_static_library, try_find_native_static_library};
use rustc_middle::bug;
use rustc_middle::middle::dependency_format::Linkage;
use rustc_middle::middle::exported_symbols;
@ -891,9 +891,15 @@ impl<'a> Linker for MsvcLinker<'a> {
}
fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
let prefix = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
let suffix = if verbatim { "" } else { ".lib" };
self.link_arg(format!("{prefix}{name}{suffix}"));
// On MSVC-like targets rustc supports static libraries using alternative naming
// scheme (`libfoo.a`) unsupported by linker, search for such libraries manually.
if let Some(path) = try_find_native_static_library(self.sess, name, verbatim) {
self.link_staticlib_by_path(&path, whole_archive);
} else {
let prefix = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
let suffix = if verbatim { "" } else { ".lib" };
self.link_arg(format!("{prefix}{name}{suffix}"));
}
}
fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {

View File

@ -0,0 +1,2 @@
#[no_mangle]
pub extern "C" fn native_lib_alt_naming() {}

View File

@ -0,0 +1,15 @@
// On MSVC the alternative naming format for static libraries (`libfoo.a`) is accepted in addition
// to the default format (`foo.lib`).
//REMOVE@ only-msvc
use run_make_support::rustc;
fn main() {
// Prepare the native library.
rustc().input("native.rs").crate_type("staticlib").output("libnative.a").run();
// Try to link to it from both a rlib and a bin.
rustc().input("rust.rs").crate_type("rlib").arg("-lstatic=native").run();
rustc().input("rust.rs").crate_type("bin").arg("-lstatic=native").run();
}

View File

@ -0,0 +1 @@
pub fn main() {}