Skip to content
Open
Changes from 1 commit
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
Next Next commit
feat: support build and link dynamic library
  • Loading branch information
westhide committed Mar 30, 2025
commit 21f2b008629125c7acad8e2492e30869c08b60b8
59 changes: 47 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
Contributor

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
Contributor

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,22 @@ 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 lib_name = if lib_striped.ends_with(".a") {
&lib_striped[..lib_striped.len() - 2]
} else if lib_striped.ends_with(".so") {
&lib_striped[..lib_striped.len() - 3]
} else {
lib_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 +1422,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
Contributor

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
Contributor

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
Contributor

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 +1465,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
Loading