Skip to content

Proposal: ability to statically link against C++ stdlib #1497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 39 additions & 8 deletions dev-tools/cc-test/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,24 @@ fn main() {
return;
}

let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
fs::remove_dir_all(&out).unwrap();
fs::create_dir(&out).unwrap();
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
fs::remove_dir_all(&out_dir).unwrap();
fs::create_dir(&out_dir).unwrap();

// The following are builds where we want to capture the output (i.e. stdout and
// stderr). We do that by re-running _this_ executable and passing in the
// action as the first argument.
run_forked_capture_output(&out, "metadata-on");
run_forked_capture_output(&out, "metadata-off");
run_forked_capture_output(&out_dir, "metadata-on");
run_forked_capture_output(&out_dir, "metadata-off");

run_forked_capture_output(&out, "warnings-off");
run_forked_capture_output(&out_dir, "warnings-off");
if cc::Build::new().get_compiler().is_like_msvc() {
// MSVC doesn't output warnings to stderr, so we can't capture them.
// the test will use this env var to know whether to run the test.
println!("cargo:rustc-env=TEST_WARNINGS_ON=0");
} else {
println!("cargo:rustc-env=TEST_WARNINGS_ON=1");
run_forked_capture_output(&out, "warnings-on");
run_forked_capture_output(&out_dir, "warnings-on");
}

let mut build = cc::Build::new();
Expand Down Expand Up @@ -104,7 +104,7 @@ fn main() {
// Test that the `windows_registry` module will set PATH by looking for
// nmake which runs vanilla cl, and then also test it after we remove all
// the relevant env vars from our own process.
let out = out.join("tmp");
let out = out_dir.join("tmp");
fs::create_dir(&out).unwrap();
println!("nmake 1");
let status = cc::windows_registry::find(&target, "nmake.exe")
Expand Down Expand Up @@ -173,6 +173,37 @@ fn main() {
let out = cc::Build::new().file("src/expand.c").expand();
let out = String::from_utf8(out).unwrap();
assert!(out.contains("hello world"));

// Test static linking of stdc++ on Linux
#[cfg(target_os = "linux")]
{
// Rust linker has no problem linking against dynamic libraries, for instance
// it doesn't require any additional steps to link against system
// `libstdc++.so`, but if we emit `cargo:rustc-link-lib=static=stdc++`, it will
// not be able to find `libstdc++.a` file despite it almost always located next to
// `libstdc++.so`. So symlinking to OUT dir solves the problem

let mut cmd = Command::new("g++");
cmd.arg("--print-file-name=libstdc++.a");
if arch == "i686" {
cmd.arg("-m32");
}
let libstdc_path: PathBuf =
String::from_utf8(cmd.output().expect("Failed to run g++").stdout)
.unwrap()
.trim()
.into();

let out_stdlib = out_dir.join("libstdc++.a");
std::os::unix::fs::symlink(libstdc_path, out_stdlib).unwrap();

cc::Build::new()
.file("src/baz.cpp")
.cpp(true)
.cpp_link_stdlib("stdc++")
.cpp_link_stdlib_static(true)
.compile("baz");
}
}

#[track_caller]
Expand Down
34 changes: 32 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ pub struct Build {
files: Vec<Arc<Path>>,
cpp: bool,
cpp_link_stdlib: Option<Option<Arc<str>>>,
cpp_link_stdlib_static: bool,
cpp_set_stdlib: Option<Arc<str>>,
cuda: bool,
cudart: Option<Arc<str>>,
Expand Down Expand Up @@ -432,6 +433,7 @@ impl Build {
static_flag: None,
cpp: false,
cpp_link_stdlib: None,
cpp_link_stdlib_static: false,
cpp_set_stdlib: None,
cuda: false,
cudart: None,
Expand Down Expand Up @@ -951,6 +953,27 @@ impl Build {
self
}

/// Force linker to statically link C++ stdlib. By default cc-rs will emit
/// rustc-link flag to link against system C++ stdlib (e.g. libstdc++.so, libc++.so)
/// Provide value of `true` if linking against system library is not desired
///
/// Note that for `wasm32` target C++ stdlib will always be linked statically
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.cpp")
/// .cpp(true)
/// .cpp_link_stdlib("stdc++")
/// .cpp_link_stdlib_static(true)
/// .compile("foo");
/// ```
pub fn cpp_link_stdlib_static(&mut self, is_static: bool) -> &mut Build {
self.cpp_link_stdlib_static = is_static;
self
}

/// Force the C++ compiler to use the specified standard library.
///
/// Setting this option will automatically set `cpp_link_stdlib` to the same
Expand Down Expand Up @@ -1482,8 +1505,15 @@ impl Build {
// Add specific C++ libraries, if enabled.
if self.cpp {
if let Some(stdlib) = self.get_cpp_link_stdlib()? {
self.cargo_output
.print_metadata(&format_args!("cargo:rustc-link-lib={}", stdlib.display()));
if self.cpp_link_stdlib_static {
self.cargo_output.print_metadata(&format_args!(
"cargo:rustc-link-lib=static={}",
stdlib.display()
));
} else {
self.cargo_output
.print_metadata(&format_args!("cargo:rustc-link-lib={}", stdlib.display()));
}
}
// Link c++ lib from WASI sysroot
if target.arch == "wasm32" {
Expand Down
Loading