Skip to content

Commit 05bd36d

Browse files
committed
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
1 parent a1c36c6 commit 05bd36d

File tree

4 files changed

+28
-4
lines changed

4 files changed

+28
-4
lines changed

compiler/rustc_codegen_ssa/src/back/linker.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::{env, iter, mem, str};
77

88
use cc::windows_registry;
99
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
10-
use rustc_metadata::find_native_static_library;
10+
use rustc_metadata::{find_native_static_library, try_find_native_static_library};
1111
use rustc_middle::bug;
1212
use rustc_middle::middle::dependency_format::Linkage;
1313
use rustc_middle::middle::exported_symbols;
@@ -891,9 +891,15 @@ impl<'a> Linker for MsvcLinker<'a> {
891891
}
892892

893893
fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
894-
let prefix = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
895-
let suffix = if verbatim { "" } else { ".lib" };
896-
self.link_arg(format!("{prefix}{name}{suffix}"));
894+
// On MSVC-like targets rustc supports static libraries using alternative naming
895+
// scheme (`libfoo.a`) unsupported by linker, search for such libraries manually.
896+
if let Some(path) = try_find_native_static_library(self.sess, name, verbatim) {
897+
self.link_staticlib_by_path(&path, whole_archive);
898+
} else {
899+
let prefix = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
900+
let suffix = if verbatim { "" } else { ".lib" };
901+
self.link_arg(format!("{prefix}{name}{suffix}"));
902+
}
897903
}
898904

899905
fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#[no_mangle]
2+
pub extern "C" fn native_lib_alt_naming() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// On MSVC the alternative naming format for static libraries (`libfoo.a`) is accepted in addition
2+
// to the default format (`foo.lib`).
3+
4+
//REMOVE@ only-msvc
5+
6+
use run_make_support::rustc;
7+
8+
fn main() {
9+
// Prepare the native library.
10+
rustc().input("native.rs").crate_type("staticlib").output("libnative.a").run();
11+
12+
// Try to link to it from both a rlib and a bin.
13+
rustc().input("rust.rs").crate_type("rlib").arg("-lstatic=native").run();
14+
rustc().input("rust.rs").crate_type("bin").arg("-lstatic=native").run();
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pub fn main() {}

0 commit comments

Comments
 (0)