Skip to content

feat: support build and link dynamic library #1444

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion src/command_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl CargoOutput {
warnings: true,
output: OutputKind::Forward,
debug: match std::env::var_os("CC_ENABLE_DEBUG_OUTPUT") {
Some(v) => v != "0" && v != "false" && v != "",
Some(v) => v != "0" && v != "false" && !v.is_empty(),
None => false,
},
checked_dbg_var: Arc::new(AtomicBool::new(false)),
Expand Down
4 changes: 2 additions & 2 deletions src/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ impl<'this> RustcCodegenFlags<'this> {
};

let clang_or_gnu =
matches!(family, ToolFamily::Clang { .. }) || matches!(family, ToolFamily::Gnu { .. });
matches!(family, ToolFamily::Clang { .. }) || matches!(family, ToolFamily::Gnu);

// Flags shared between clang and gnu
if clang_or_gnu {
Expand Down Expand Up @@ -315,7 +315,7 @@ impl<'this> RustcCodegenFlags<'this> {
}
}
}
ToolFamily::Gnu { .. } => {}
ToolFamily::Gnu => {}
ToolFamily::Msvc { .. } => {
// https://learn.microsoft.com/en-us/cpp/build/reference/guard-enable-control-flow-guard
if let Some(value) = self.control_flow_guard {
Expand Down
55 changes: 43 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ pub struct Build {
shell_escaped_flags: Option<bool>,
build_cache: Arc<BuildCache>,
inherit_rustflags: bool,
link_shared_flag: bool,
}

/// Represents the types of errors that may occur while using cc-rs.
Expand Down Expand Up @@ -459,6 +460,7 @@ impl Build {
shell_escaped_flags: None,
build_cache: Arc::default(),
inherit_rustflags: true,
link_shared_flag: false,
}
}

Expand Down Expand Up @@ -1227,6 +1229,14 @@ impl Build {
self
}

/// Configure whether cc should build dynamic library and link with `rustc-link-lib=dylib`
///
/// This option defaults to `false`.
pub fn link_shared_flag(&mut self, link_shared_flag: bool) -> &mut Build {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When reading this as a user, it is not really clear how this differs from shared_flag.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stated another way: When would you ever want shared_flag(true) but not link_shared_flag(true)? And vice-versa?

self.link_shared_flag = link_shared_flag;
self
}

#[doc(hidden)]
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
where
Expand Down Expand Up @@ -1380,6 +1390,18 @@ impl Build {
Ok(is_supported)
}

fn get_canonical_library_names(name: &str) -> (&str, String, String) {
let lib_striped = name.strip_prefix("lib").unwrap_or(name);
let static_striped = lib_striped.strip_suffix(".a").unwrap_or(lib_striped);
let lib_name = lib_striped.strip_suffix(".so").unwrap_or(static_striped);

(
lib_name,
format!("lib{lib_name}.a"),
format!("lib{lib_name}.so"),
)
}

/// Run the compiler, generating the file `output`
///
/// This will return a result instead of panicking; see [`Self::compile()`] for
Expand All @@ -1396,21 +1418,25 @@ impl Build {
}
}

let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
(&output[3..output.len() - 2], output.to_owned())
} else {
let mut gnu = String::with_capacity(5 + output.len());
gnu.push_str("lib");
gnu.push_str(output);
gnu.push_str(".a");
(output, gnu)
};
let (lib_name, static_name, dynlib_name) = Self::get_canonical_library_names(output);
let dst = self.get_out_dir()?;

let objects = objects_from_files(&self.files, &dst)?;

self.compile_objects(&objects)?;
self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;

if self.link_shared_flag {
let objects = objects.iter().map(|o| o.dst.clone()).collect::<Vec<_>>();

let mut command = self.try_get_compiler()?.to_command();
let cmd = command
.args(["-shared", "-o"])
.arg(dst.join(dynlib_name))
.args(&objects);
run(cmd, &self.cargo_output)?;
}

self.assemble(lib_name, &dst.join(static_name), &objects)?;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need to run assemble if it's already dynamically linked?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we consider support dll on windows?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need to run assemble if it's already dynamically linked?

Sure, fixed.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we consider support dll on windows?

Can you elaborate on that please?

Copy link
Author

@westhide westhide Mar 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Windows ddl is complicated, i have not idea how to add a dynamic library test case for it. It's weird as cl.exe require a main function to build a dll library.

With this source file, it will cause a Entry Point Not Found error

#include <windows.h>
void msvc() {}

Test pass if add a main function

#include <windows.h>
void msvc() {}
void main() {}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for explanation, I'm ok with it not tested, if you have time to add another test for it I would greatly appreciate


let target = self.get_target()?;
if target.env == "msvc" {
Expand All @@ -1435,8 +1461,13 @@ impl Build {
}

if self.link_lib_modifiers.is_empty() {
self.cargo_output
.print_metadata(&format_args!("cargo:rustc-link-lib=static={}", lib_name));
if self.link_shared_flag {
self.cargo_output
.print_metadata(&format_args!("cargo:rustc-link-lib=dylib={}", lib_name));
} else {
self.cargo_output
.print_metadata(&format_args!("cargo:rustc-link-lib=static={}", lib_name));
}
} else {
self.cargo_output.print_metadata(&format_args!(
"cargo:rustc-link-lib=static:{}={}",
Expand Down
12 changes: 6 additions & 6 deletions src/target/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,13 +477,13 @@ mod tests {
let (full_arch, _rest) = target.split_once('-').expect("target to have arch");

let mut target = TargetInfo {
full_arch: full_arch.into(),
arch: "invalid-none-set".into(),
vendor: "invalid-none-set".into(),
os: "invalid-none-set".into(),
env: "invalid-none-set".into(),
full_arch,
arch: "invalid-none-set",
vendor: "invalid-none-set",
os: "invalid-none-set",
env: "invalid-none-set",
// Not set in older Rust versions
abi: "".into(),
abi: "",
};

for cfg in cfgs.lines() {
Expand Down
2 changes: 1 addition & 1 deletion tests/cc_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ fn clang_cl() {
for exe_suffix in ["", ".exe"] {
let test = Test::clang();
let bin = format!("clang{exe_suffix}");
env::set_var("CC", &format!("{bin} --driver-mode=cl"));
env::set_var("CC", format!("{bin} --driver-mode=cl"));
let test_compiler = |build: cc::Build| {
let compiler = build.get_compiler();
assert_eq!(compiler.path(), Path::new(&*bin));
Expand Down
4 changes: 2 additions & 2 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,8 @@ fn gnu_apple_sysroot() {
test.shim("fake-gcc")
.gcc()
.compiler("fake-gcc")
.target(&target)
.host(&target)
.target(target)
.host(target)
.file("foo.c")
.compile("foo");

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documentation on compile should also be updated to reflect the new renaming rules.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we actually want to support shared libraries, we should consider a .linker and .get_linker similar to .archiver and .get_archiver, as well as maybe allowing overriding the linker with an LD env var (?)

Though if we allow using a raw linker (e.g. invoke rust-lld binary instead of cc), we're getting into hairy territory of needing to know how to invoke the linker if it's not a compiler driver.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Which again is why I'm really not in favour of it).

Expand Down