Skip to content

Commit 7f7ea1c

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 d4b81fe commit 7f7ea1c

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
@@ -1408,9 +1408,7 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker,
14081408
}
14091409
}
14101410

1411-
// Link in all of our upstream crates' native dependencies. Remember that
1412-
// all of these upstream native dependencies are all non-static
1413-
// dependencies. We've got two cases then:
1411+
// Link in all of our upstream crates' native dependencies. We have two cases:
14141412
//
14151413
// 1. The upstream crate is an rlib. In this case we *must* link in the
14161414
// native dependency because the rlib is just an archive.
@@ -1453,7 +1451,19 @@ fn add_upstream_native_libraries(cmd: &mut dyn Linker,
14531451
continue
14541452
}
14551453
match lib.kind {
1456-
NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1454+
NativeLibraryKind::NativeUnknown => {
1455+
// On some targets, like Linux, linking a static executable inhibits using
1456+
// dylibs at all. Force native libraries to be static, even if for example
1457+
// an upstream rlib was originally linked against a native shared library.
1458+
if crate_type == config::CrateType::Executable
1459+
&& sess.crt_static()
1460+
&& !sess.target.target.options.crt_static_allows_dylibs
1461+
{
1462+
cmd.link_staticlib(&name.as_str())
1463+
} else {
1464+
cmd.link_dylib(&name.as_str())
1465+
}
1466+
},
14571467
NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
14581468
NativeLibraryKind::NativeStaticNobundle => {
14591469
// Link "static-nobundle" native libs only if the crate they originate from

0 commit comments

Comments
 (0)