-
Notifications
You must be signed in to change notification settings - Fork 504
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -332,6 +332,8 @@ pub struct Build { | |
shell_escaped_flags: Option<bool>, | ||
build_cache: Arc<BuildCache>, | ||
inherit_rustflags: bool, | ||
link_shared_flag: bool, | ||
shared_lib_out_dir: Option<Arc<Path>>, | ||
} | ||
|
||
/// Represents the types of errors that may occur while using cc-rs. | ||
|
@@ -459,6 +461,8 @@ impl Build { | |
shell_escaped_flags: None, | ||
build_cache: Arc::default(), | ||
inherit_rustflags: true, | ||
link_shared_flag: false, | ||
shared_lib_out_dir: None, | ||
} | ||
} | ||
|
||
|
@@ -1227,6 +1231,22 @@ 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 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Stated another way: When would you ever want |
||
self.link_shared_flag = link_shared_flag; | ||
self | ||
} | ||
|
||
/// Configures the output directory where shared library will be located. | ||
/// | ||
/// This option defaults to `out_dir`. | ||
pub fn shared_lib_out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build { | ||
self.shared_lib_out_dir = Some(out_dir.as_ref().into()); | ||
self | ||
} | ||
Comment on lines
+1242
to
+1248
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm against adding this, I think the user should copy it from |
||
|
||
#[doc(hidden)] | ||
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build | ||
where | ||
|
@@ -1380,6 +1400,28 @@ impl Build { | |
Ok(is_supported) | ||
} | ||
|
||
/// Get canonical library names for `output` | ||
fn get_canonical_library_names<'a>( | ||
&self, | ||
output: &'a str, | ||
) -> Result<(&'a str, String, String), Error> { | ||
let lib_striped = output.strip_prefix("lib").unwrap_or(output); | ||
let static_striped = lib_striped.strip_suffix(".a").unwrap_or(lib_striped); | ||
|
||
let dyn_ext = if self.get_target()?.env == "msvc" { | ||
".dll" | ||
} else { | ||
".so" | ||
}; | ||
let lib_name = lib_striped.strip_suffix(dyn_ext).unwrap_or(static_striped); | ||
|
||
Ok(( | ||
lib_name, | ||
format!("lib{lib_name}.a"), | ||
format!("lib{lib_name}{dyn_ext}"), | ||
)) | ||
} | ||
|
||
/// Run the compiler, generating the file `output` | ||
/// | ||
/// This will return a result instead of panicking; see [`Self::compile()`] for | ||
|
@@ -1396,21 +1438,26 @@ 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 cmd = self.try_get_compiler()?.to_command(); | ||
let dynlib_path = dst.join(&dynlib_name); | ||
cmd.args(["-shared", "-o"]).arg(&dynlib_path).args(&objects); | ||
run(&mut cmd, &self.cargo_output)?; | ||
if let Some(out_dir) = &self.shared_lib_out_dir { | ||
fs::copy(dynlib_path, out_dir.join(&dynlib_name))?; | ||
} | ||
} else { | ||
self.assemble(lib_name, &dst.join(static_name), &objects)?; | ||
} | ||
|
||
let target = self.get_target()?; | ||
if target.env == "msvc" { | ||
|
@@ -1435,8 +1482,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:{}={}", | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -354,6 +354,37 @@ fn gnu_shared() { | |
test.cmd(0).must_have("-shared").must_not_have("-static"); | ||
} | ||
|
||
#[test] | ||
#[cfg(target_os = "linux")] | ||
fn gnu_link_shared() { | ||
use std::process::Command; | ||
|
||
let output = Command::new("rustc").arg("-vV").output().unwrap(); | ||
NobodyXu marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let stdout_buf = String::from_utf8(output.stdout).unwrap(); | ||
let target = stdout_buf | ||
.lines() | ||
.find_map(|l| l.strip_prefix("host: ")) | ||
.unwrap(); | ||
|
||
reset_env(); | ||
let test = Test::gnu(); | ||
let root_dir = env!("CARGO_MANIFEST_DIR"); | ||
let src = format!("{root_dir}/dev-tools/cc-test/src/foo.c"); | ||
|
||
cc::Build::new() | ||
.host(target) | ||
.target(target) | ||
.opt_level(2) | ||
.out_dir(test.td.path()) | ||
.file(&src) | ||
.shared_flag(true) | ||
.static_flag(false) | ||
.link_shared_flag(true) | ||
.compile("foo"); | ||
|
||
assert!(test.td.path().join("libfoo.so").exists()); | ||
} | ||
|
||
#[test] | ||
fn gnu_flag_if_supported() { | ||
reset_env(); | ||
|
@@ -532,8 +563,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"); | ||
|
||
NobodyXu marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Documentation on There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If we actually want to support shared libraries, we should consider a Though if we allow using a raw linker (e.g. invoke There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (Which again is why I'm really not in favour of it). |
||
|
Uh oh!
There was an error while loading. Please reload this page.