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 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
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
76 changes: 64 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
}
}

Expand Down Expand Up @@ -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 {
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
}

/// 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
Copy link
Collaborator

Choose a reason for hiding this comment

The 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 out_dir if they want the final shared library to be placed elsewhere.


#[doc(hidden)]
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
where
Expand Down Expand Up @@ -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
Expand All @@ -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" {
Expand All @@ -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:{}={}",
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
35 changes: 33 additions & 2 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
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();
Expand Down Expand Up @@ -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");

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