Skip to content

Commit 859624e

Browse files
committed
Require static native libraries when linking static executables
On ELF targets like Linux, gcc/ld will create a dynamically-linked executable without warning, even when passed `-static`, when asked to link to a `.so`. Avoid this confusing and unintended behavior by always using the static version of libraries when trying to link static executables. Fixes rust-lang#54243
1 parent c4565fa commit 859624e

File tree

1 file changed

+14
-4
lines changed
  • src/librustc_codegen_llvm/back

1 file changed

+14
-4
lines changed

src/librustc_codegen_llvm/back/link.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1413,9 +1413,7 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker,
14131413
}
14141414
}
14151415

1416-
// Link in all of our upstream crates' native dependencies. Remember that
1417-
// all of these upstream native dependencies are all non-static
1418-
// dependencies. We've got two cases then:
1416+
// Link in all of our upstream crates' native dependencies. We have two cases:
14191417
//
14201418
// 1. The upstream crate is an rlib. In this case we *must* link in the
14211419
// native dependency because the rlib is just an archive.
@@ -1458,7 +1456,19 @@ fn add_upstream_native_libraries(cmd: &mut dyn Linker,
14581456
continue
14591457
}
14601458
match lib.kind {
1461-
NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1459+
NativeLibraryKind::NativeUnknown => {
1460+
// On some targets, like Linux, linking a static executable inhibits using
1461+
// dylibs at all. Force native libraries to be static, even if for example
1462+
// an upstream rlib was originally linked against a native shared library.
1463+
if crate_type == config::CrateType::Executable
1464+
&& sess.crt_static()
1465+
&& !sess.target.target.options.crt_static_allows_dylibs
1466+
{
1467+
cmd.link_staticlib(&name.as_str())
1468+
} else {
1469+
cmd.link_dylib(&name.as_str())
1470+
}
1471+
},
14621472
NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
14631473
NativeLibraryKind::NativeStaticNobundle => {
14641474
// Link "static-nobundle" native libs only if the crate they originate from

0 commit comments

Comments
 (0)