Skip to content

Commit 2d60183

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 #54243
1 parent f694222 commit 2d60183

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

+14-4
Original file line numberDiff line numberDiff line change
@@ -1412,9 +1412,7 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker,
14121412
}
14131413
}
14141414

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

0 commit comments

Comments
 (0)