cc/lib.rs
1//! A library for [Cargo build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html)
2//! to compile a set of C/C++/assembly/CUDA files into a static archive for Cargo
3//! to link into the crate being built. This crate does not compile code itself;
4//! it calls out to the default compiler for the platform. This crate will
5//! automatically detect situations such as cross compilation and
6//! [various environment variables](#external-configuration-via-environment-variables) and will build code appropriately.
7//!
8//! # Example
9//!
10//! First, you'll want to both add a build script for your crate (`build.rs`) and
11//! also add this crate to your `Cargo.toml` via:
12//!
13//! ```toml
14//! [build-dependencies]
15//! cc = "1.0"
16//! ```
17//!
18//! Next up, you'll want to write a build script like so:
19//!
20//! ```rust,no_run
21//! // build.rs
22//! cc::Build::new()
23//! .file("foo.c")
24//! .file("bar.c")
25//! .compile("foo");
26//! ```
27//!
28//! And that's it! Running `cargo build` should take care of the rest and your Rust
29//! application will now have the C files `foo.c` and `bar.c` compiled into a file
30//! named `libfoo.a`. If the C files contain
31//!
32//! ```c
33//! void foo_function(void) { ... }
34//! ```
35//!
36//! and
37//!
38//! ```c
39//! int32_t bar_function(int32_t x) { ... }
40//! ```
41//!
42//! you can call them from Rust by declaring them in
43//! your Rust code like so:
44//!
45//! ```rust,no_run
46//! extern "C" {
47//! fn foo_function();
48//! fn bar_function(x: i32) -> i32;
49//! }
50//!
51//! pub fn call() {
52//! unsafe {
53//! foo_function();
54//! bar_function(42);
55//! }
56//! }
57//!
58//! fn main() {
59//! call();
60//! }
61//! ```
62//!
63//! See [the Rustonomicon](https://doc.rust-lang.org/nomicon/ffi.html) for more details.
64//!
65//! # External configuration via environment variables
66//!
67//! To control the programs and flags used for building, the builder can set a
68//! number of different environment variables.
69//!
70//! * `CFLAGS` - a series of space separated flags passed to compilers. Note that
71//! individual flags cannot currently contain spaces, so doing
72//! something like: `-L=foo\ bar` is not possible.
73//! * `CC` - the actual C compiler used. Note that this supports passing a known
74//! wrapper via `sccache cc`. This compiler must understand the `-c` flag. For
75//! certain `TARGET`s, it also is assumed to know about other flags (most
76//! common is `-fPIC`).
77//! ccache, distcc, sccache, icecc, cachepot, buildcache and kache are supported,
78//! for sccache, simply set `CC` to `sccache cc`.
79//! For other custom `CC` wrapper, just set `CC_KNOWN_WRAPPER_CUSTOM`
80//! to the custom wrapper used in `CC`.
81//! * `AR` - the `ar` (archiver) executable to use to build the static library.
82//! * `CRATE_CC_NO_DEFAULTS` - the default compiler flags may cause conflicts in
83//! some cross compiling scenarios. Setting this variable
84//! will disable the generation of default compiler
85//! flags.
86//! * `CC_ENABLE_DEBUG_OUTPUT` - if set, compiler command invocations and exit codes will
87//! be logged to stdout. This is useful for debugging build script issues, but can be
88//! overly verbose for normal use.
89//! * `CC_SHELL_ESCAPED_FLAGS` - if set, `*FLAGS` will be parsed as if they were shell
90//! arguments (similar to `make` and `cmake`) rather than splitting them on each space.
91//! For example, with `CFLAGS='a "b c"'`, the compiler will be invoked with 2 arguments -
92//! `a` and `b c` - rather than 3: `a`, `"b` and `c"`.
93//! * `CXX...` - see [C++ Support](#c-support).
94//! * `CC_FORCE_DISABLE` - If set, `cc` will never run any [`Command`]s, and methods that
95//! would return an [`Error`]. This is intended for use by third-party build systems
96//! which want to be absolutely sure that they are in control of building all
97//! dependencies. Note that operations that return [`Tool`]s such as
98//! [`Build::get_compiler`] may produce less accurate results as in some cases `cc` runs
99//! commands in order to locate compilers. Additionally, this does nothing to prevent
100//! users from running [`Tool::to_command`] and executing the [`Command`] themselves.
101//! * `RUSTC_WRAPPER` - If set, the specified command will be prefixed to the compiler
102//! command. This is useful for projects that want to use
103//! [sccache](https://github.com/mozilla/sccache),
104//! [buildcache](https://gitlab.com/bits-n-bites/buildcache),
105//! [cachepot](https://github.com/paritytech/cachepot), or
106//! [kache](https://github.com/kunobi-ninja/kache).
107//!
108//! Furthermore, projects using this crate may specify custom environment variables
109//! to be inspected, for example via the `Build::try_flags_from_environment`
110//! function. Consult the project’s own documentation or its use of the `cc` crate
111//! for any additional variables it may use.
112//!
113//! Each of these variables can also be supplied with certain prefixes and suffixes,
114//! in the following prioritized order:
115//!
116//! 1. `<var>_<target>` - for example, `CC_x86_64-unknown-linux-gnu` or `CC_thumbv8m.main-none-eabi`
117//! 2. `<var>_<target_with_underscores>` - for example, `CC_x86_64_unknown_linux_gnu` or `CC_thumbv8m_main_none_eabi` (both periods and underscores are replaced)
118//! 3. `<build-kind>_<var>` - for example, `HOST_CC` or `TARGET_CFLAGS`
119//! 4. `<var>` - a plain `CC`, `AR` as above.
120//!
121//! If none of these variables exist, cc-rs uses built-in defaults.
122//!
123//! In addition to the above optional environment variables, `cc-rs` has some
124//! functions with hard requirements on some variables supplied by [cargo's
125//! build-script driver][cargo] that it has the `TARGET`, `OUT_DIR`, `OPT_LEVEL`,
126//! and `HOST` variables.
127//!
128//! [cargo]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#inputs-to-the-build-script
129//!
130//! # Optional features
131//!
132//! ## Parallel
133//!
134//! Currently cc-rs supports parallel compilation (think `make -jN`) but this
135//! feature is turned off by default. To enable cc-rs to compile C/C++ in parallel,
136//! you can change your dependency to:
137//!
138//! ```toml
139//! [build-dependencies]
140//! cc = { version = "1.0", features = ["parallel"] }
141//! ```
142//!
143//! By default cc-rs will limit parallelism to `$NUM_JOBS`, or if not present it
144//! will limit it to the number of cpus on the machine. If you are using cargo,
145//! use `-jN` option of `build`, `test` and `run` commands as `$NUM_JOBS`
146//! is supplied by cargo.
147//!
148//! # Compile-time Requirements
149//!
150//! To work properly this crate needs access to a C compiler when the build script
151//! is being run. This crate does not ship a C compiler with it. The compiler
152//! required varies per platform, but there are three broad categories:
153//!
154//! * Unix platforms require `cc` to be the C compiler. This can be found by
155//! installing cc/clang on Linux distributions and Xcode on macOS, for example.
156//! * Windows platforms targeting MSVC (e.g. your target name ends in `-msvc`)
157//! require Visual Studio to be installed. `cc-rs` attempts to locate it, and
158//! if it fails, `cl.exe` is expected to be available in `PATH`. This can be
159//! set up by running the appropriate developer tools shell.
160//! * When using `prefer_clang_cl_over_msvc`, make sure that the `C++ Clang compiler for Windows` component
161//! is installed through the Visual Studio Installer, so that `cc-rs` can find `clang-cl.exe`.
162//! * Windows platforms targeting MinGW (e.g. your target name ends in `-gnu`)
163//! require `cc` to be available in `PATH`. We recommend the
164//! [MinGW-w64](https://www.mingw-w64.org/) distribution.
165//! You may also acquire it via
166//! [MSYS2](https://www.msys2.org/), as explained [here][msys2-help]. Make sure
167//! to install the appropriate architecture corresponding to your installation of
168//! rustc. GCC from older [MinGW](http://www.mingw.org/) project is compatible
169//! only with 32-bit rust compiler.
170//!
171//! [msys2-help]: https://github.com/rust-lang/rust/blob/master/INSTALL.md#building-on-windows
172//!
173//! # C++ support
174//!
175//! `cc-rs` supports C++ libraries compilation by using the `cpp` method on
176//! `Build`:
177//!
178//! ```rust,no_run
179//! cc::Build::new()
180//! .cpp(true) // Switch to C++ library compilation.
181//! .file("foo.cpp")
182//! .compile("foo");
183//! ```
184//!
185//! For C++ libraries, the `CXX` and `CXXFLAGS` environment variables are used instead of `CC` and `CFLAGS`.
186//!
187//! The C++ standard library may be linked to the crate target. By default it's `libc++` for macOS, FreeBSD, and OpenBSD, `libc++_shared` for Android, nothing for MSVC, and `libstdc++` for anything else. It can be changed in one of two ways:
188//!
189//! 1. by using the `cpp_link_stdlib` method on `Build`:
190//! ```rust,no_run
191//! cc::Build::new()
192//! .cpp(true)
193//! .file("foo.cpp")
194//! .cpp_link_stdlib("stdc++") // use libstdc++
195//! .compile("foo");
196//! ```
197//! 2. by setting the `CXXSTDLIB` environment variable.
198//!
199//! In particular, for Android you may want to [use `c++_static` if you have at most one shared library](https://developer.android.com/ndk/guides/cpp-support).
200//!
201//! Remember that C++ does name mangling so `extern "C"` might be required to enable Rust linker to find your functions.
202//!
203//! # CUDA C++ support
204//!
205//! `cc-rs` also supports compiling CUDA C++ libraries by using the `cuda` method
206//! on `Build`:
207//!
208//! ```rust,no_run
209//! cc::Build::new()
210//! // Switch to CUDA C++ library compilation using NVCC.
211//! .cuda(true)
212//! .cudart("static")
213//! // Generate code for Maxwell (GTX 970, 980, 980 Ti, Titan X).
214//! .flag("-gencode").flag("arch=compute_52,code=sm_52")
215//! // Generate code for Maxwell (Jetson TX1).
216//! .flag("-gencode").flag("arch=compute_53,code=sm_53")
217//! // Generate code for Pascal (GTX 1070, 1080, 1080 Ti, Titan Xp).
218//! .flag("-gencode").flag("arch=compute_61,code=sm_61")
219//! // Generate code for Pascal (Tesla P100).
220//! .flag("-gencode").flag("arch=compute_60,code=sm_60")
221//! // Generate code for Pascal (Jetson TX2).
222//! .flag("-gencode").flag("arch=compute_62,code=sm_62")
223//! // Generate code in parallel
224//! .flag("-t0")
225//! .file("bar.cu")
226//! .compile("bar");
227//! ```
228//!
229//! # Speed up compilation with sccache
230//!
231//! `cc-rs` does not handle incremental compilation like `make` or `ninja`. It
232//! always compiles the all sources, no matter if they have changed or not.
233//! This would be time-consuming in large projects. To save compilation time,
234//! you can use [sccache](https://github.com/mozilla/sccache) by setting
235//! environment variable `RUSTC_WRAPPER=sccache`, which will use cached `.o`
236//! files if the sources are unchanged.
237
238#![doc(html_root_url = "https://docs.rs/cc/1.0")]
239
240use std::borrow::Cow;
241use std::collections::HashMap;
242use std::env;
243use std::ffi::{OsStr, OsString};
244use std::fmt::{self, Display};
245use std::fs;
246use std::io::{self, Write};
247use std::path::{Component, Path, PathBuf};
248use std::process::{Command, Stdio};
249use std::sync::{Arc, RwLock};
250
251use shlex::Shlex;
252
253#[cfg(feature = "parallel")]
254mod parallel;
255
256mod target;
257use self::target::*;
258
259/// A helper module to looking for windows-specific tools:
260/// 1. On Windows host, probe the Windows Registry if needed;
261/// 2. On non-Windows host, check specified environment variables.
262pub mod windows_registry {
263 // Regardless of whether this should be in this crate's public API,
264 // it has been since 2015, so don't break it.
265
266 /// Attempts to find a tool within an MSVC installation using the Windows
267 /// registry as a point to search from.
268 ///
269 /// The `arch_or_target` argument is the architecture or the Rust target name
270 /// that the tool should work for (e.g. compile or link for). The supported
271 /// architecture names are:
272 /// - `"x64"` or `"x86_64"`
273 /// - `"arm64"` or `"aarch64"`
274 /// - `"arm64ec"`
275 /// - `"x86"`, `"i586"` or `"i686"`
276 /// - `"arm"` or `"thumbv7a"`
277 ///
278 /// The `tool` argument is the tool to find. Supported tools include:
279 /// - MSVC tools: `cl.exe`, `link.exe`, `lib.exe`, etc.
280 /// - `MSBuild`: `msbuild.exe`
281 /// - Visual Studio IDE: `devenv.exe`
282 /// - Clang/LLVM tools: `clang.exe`, `clang++.exe`, `clang-*.exe`, `llvm-*.exe`, `lld.exe`, etc.
283 ///
284 /// This function will return `None` if the tool could not be found, or it will
285 /// return `Some(cmd)` which represents a command that's ready to execute the
286 /// tool with the appropriate environment variables set.
287 ///
288 /// Note that this function always returns `None` for non-MSVC targets (if a
289 /// full target name was specified).
290 pub fn find(arch_or_target: &str, tool: &str) -> Option<std::process::Command> {
291 ::find_msvc_tools::find(arch_or_target, tool)
292 }
293
294 /// A version of Visual Studio
295 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
296 #[non_exhaustive]
297 pub enum VsVers {
298 /// Visual Studio 12 (2013)
299 #[deprecated = "Visual Studio 12 is no longer supported. cc will never return this value."]
300 Vs12,
301 /// Visual Studio 14 (2015)
302 Vs14,
303 /// Visual Studio 15 (2017)
304 Vs15,
305 /// Visual Studio 16 (2019)
306 Vs16,
307 /// Visual Studio 17 (2022)
308 Vs17,
309 /// Visual Studio 18 (2026)
310 Vs18,
311 }
312
313 /// Find the most recent installed version of Visual Studio
314 ///
315 /// This is used by the cmake crate to figure out the correct
316 /// generator.
317 pub fn find_vs_version() -> Result<VsVers, String> {
318 ::find_msvc_tools::find_vs_version().map(|vers| match vers {
319 #[allow(deprecated)]
320 ::find_msvc_tools::VsVers::Vs12 => VsVers::Vs12,
321 ::find_msvc_tools::VsVers::Vs14 => VsVers::Vs14,
322 ::find_msvc_tools::VsVers::Vs15 => VsVers::Vs15,
323 ::find_msvc_tools::VsVers::Vs16 => VsVers::Vs16,
324 ::find_msvc_tools::VsVers::Vs17 => VsVers::Vs17,
325 ::find_msvc_tools::VsVers::Vs18 => VsVers::Vs18,
326 _ => unreachable!("unknown VS version"),
327 })
328 }
329
330 /// Similar to the `find` function above, this function will attempt the same
331 /// operation (finding a MSVC tool in a local install) but instead returns a
332 /// [`Tool`](crate::Tool) which may be introspected.
333 pub fn find_tool(arch_or_target: &str, tool: &str) -> Option<crate::Tool> {
334 ::find_msvc_tools::find_tool(arch_or_target, tool).map(crate::Tool::from_find_msvc_tools)
335 }
336}
337
338mod command_helpers;
339use command_helpers::*;
340
341mod tool;
342pub use tool::Tool;
343use tool::{CompilerFamilyLookupCache, ToolFamily};
344
345mod tempfile;
346
347mod utilities;
348use utilities::*;
349
350mod flags;
351use flags::*;
352
353#[derive(Debug, Eq, PartialEq, Hash)]
354struct CompilerFlag {
355 compiler: Box<Path>,
356 flag: Box<OsStr>,
357}
358
359enum PrefixMapFlag {
360 Macro,
361 Debug,
362}
363
364#[derive(Debug, Default)]
365struct BuildCache {
366 apple_sdk_root_cache: RwLock<HashMap<Box<str>, Arc<OsStr>>>,
367 apple_versions_cache: RwLock<HashMap<Box<str>, Arc<str>>>,
368 cached_compiler_family: RwLock<CompilerFamilyLookupCache>,
369 known_flag_support_status_cache: RwLock<HashMap<CompilerFlag, bool>>,
370 target_info_parser: target::TargetInfoParser,
371}
372
373/// A builder for compilation of a native library.
374///
375/// A `Build` is the main type of the `cc` crate and is used to control all the
376/// various configuration options and such of a compile. You'll find more
377/// documentation on each method itself.
378#[derive(Clone, Debug)]
379pub struct Build {
380 include_directories: Vec<Arc<Path>>,
381 definitions: Vec<(Arc<str>, Option<Arc<str>>)>,
382 objects: Vec<Arc<Path>>,
383 flags: Vec<Arc<OsStr>>,
384 flags_supported: Vec<Arc<OsStr>>,
385 ar_flags: Vec<Arc<OsStr>>,
386 asm_flags: Vec<Arc<OsStr>>,
387 no_default_flags: bool,
388 files: Vec<Arc<Path>>,
389 cpp: bool,
390 cpp_link_stdlib: Option<Option<Arc<str>>>,
391 cpp_link_stdlib_static: bool,
392 cpp_set_stdlib: Option<Arc<str>>,
393 cuda: bool,
394 cudart: Option<Arc<str>>,
395 ccbin: bool,
396 std: Option<Arc<str>>,
397 target: Option<Arc<str>>,
398 /// The host compiler.
399 ///
400 /// Try to not access this directly, and instead prefer `cfg!(...)`.
401 host: Option<Arc<str>>,
402 out_dir: Option<Arc<Path>>,
403 opt_level: Option<Arc<str>>,
404 debug: Option<Arc<str>>,
405 force_frame_pointer: Option<bool>,
406 env: Vec<(Arc<OsStr>, Arc<OsStr>)>,
407 compiler: Option<Arc<Path>>,
408 archiver: Option<Arc<Path>>,
409 ranlib: Option<Arc<Path>>,
410 cargo_output: CargoOutput,
411 link_lib_modifiers: Vec<Arc<OsStr>>,
412 pic: Option<bool>,
413 use_plt: Option<bool>,
414 static_crt: Option<bool>,
415 shared_flag: Option<bool>,
416 static_flag: Option<bool>,
417 warnings_into_errors: bool,
418 warnings: Option<bool>,
419 extra_warnings: Option<bool>,
420 emit_rerun_if_env_changed: bool,
421 shell_escaped_flags: Option<bool>,
422 build_cache: Arc<BuildCache>,
423 inherit_rustflags: bool,
424 inherit_trim_paths: bool,
425 prefer_clang_cl_over_msvc: bool,
426}
427
428/// Represents the types of errors that may occur while using cc-rs.
429#[derive(Clone, Debug)]
430enum ErrorKind {
431 /// Error occurred while performing I/O.
432 IOError,
433 /// Environment variable not found, with the var in question as extra info.
434 EnvVarNotFound,
435 /// Error occurred while using external tools (ie: invocation of compiler).
436 ToolExecError,
437 /// Error occurred due to missing external tools.
438 ToolNotFound,
439 /// One of the function arguments failed validation.
440 InvalidArgument,
441 /// No known macro is defined for the compiler when discovering tool family.
442 ToolFamilyMacroNotFound,
443 /// Invalid target.
444 InvalidTarget,
445 /// Unknown target.
446 UnknownTarget,
447 /// Invalid rustc flag.
448 InvalidFlag,
449 #[cfg(feature = "parallel")]
450 /// jobserver helpthread failure
451 JobserverHelpThreadError,
452 /// `cc` has been disabled by an environment variable.
453 Disabled,
454}
455
456/// Represents an internal error that occurred, with an explanation.
457#[derive(Clone, Debug)]
458pub struct Error {
459 /// Describes the kind of error that occurred.
460 kind: ErrorKind,
461 /// More explanation of error that occurred.
462 message: Cow<'static, str>,
463}
464
465impl Error {
466 fn new(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Error {
467 Error {
468 kind,
469 message: message.into(),
470 }
471 }
472}
473
474impl From<io::Error> for Error {
475 fn from(e: io::Error) -> Error {
476 Error::new(ErrorKind::IOError, format!("{e}"))
477 }
478}
479
480impl Display for Error {
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 write!(f, "{:?}: {}", self.kind, self.message)
483 }
484}
485
486impl std::error::Error for Error {}
487
488/// Represents an object.
489///
490/// This is a source file -> object file pair.
491#[derive(Clone, Debug)]
492struct Object {
493 src: PathBuf,
494 dst: PathBuf,
495}
496
497impl Object {
498 /// Create a new source file -> object file pair.
499 fn new(src: PathBuf, dst: PathBuf) -> Object {
500 Object { src, dst }
501 }
502}
503
504/// Configure the builder.
505impl Build {
506 /// Construct a new instance of a blank set of configuration.
507 ///
508 /// This builder is finished with the [`compile`] function.
509 ///
510 /// [`compile`]: struct.Build.html#method.compile
511 pub fn new() -> Build {
512 Build {
513 include_directories: Vec::new(),
514 definitions: Vec::new(),
515 objects: Vec::new(),
516 flags: Vec::new(),
517 flags_supported: Vec::new(),
518 ar_flags: Vec::new(),
519 asm_flags: Vec::new(),
520 no_default_flags: false,
521 files: Vec::new(),
522 shared_flag: None,
523 static_flag: None,
524 cpp: false,
525 cpp_link_stdlib: None,
526 cpp_link_stdlib_static: false,
527 cpp_set_stdlib: None,
528 cuda: false,
529 cudart: None,
530 ccbin: true,
531 std: None,
532 target: None,
533 host: None,
534 out_dir: None,
535 opt_level: None,
536 debug: None,
537 force_frame_pointer: None,
538 env: Vec::new(),
539 compiler: None,
540 archiver: None,
541 ranlib: None,
542 cargo_output: CargoOutput::new(),
543 link_lib_modifiers: Vec::new(),
544 pic: None,
545 use_plt: None,
546 static_crt: None,
547 warnings: None,
548 extra_warnings: None,
549 warnings_into_errors: false,
550 emit_rerun_if_env_changed: true,
551 shell_escaped_flags: None,
552 build_cache: Arc::default(),
553 inherit_rustflags: true,
554 inherit_trim_paths: true,
555 prefer_clang_cl_over_msvc: false,
556 }
557 }
558
559 /// Add a directory to the `-I` or include path for headers
560 ///
561 /// # Example
562 ///
563 /// ```no_run
564 /// use std::path::Path;
565 ///
566 /// let library_path = Path::new("/path/to/library");
567 ///
568 /// cc::Build::new()
569 /// .file("src/foo.c")
570 /// .include(library_path)
571 /// .include("src")
572 /// .compile("foo");
573 /// ```
574 pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build {
575 self.include_directories.push(dir.as_ref().into());
576 self
577 }
578
579 /// Add multiple directories to the `-I` include path.
580 ///
581 /// # Example
582 ///
583 /// ```no_run
584 /// # use std::path::Path;
585 /// # let condition = true;
586 /// #
587 /// let mut extra_dir = None;
588 /// if condition {
589 /// extra_dir = Some(Path::new("/path/to"));
590 /// }
591 ///
592 /// cc::Build::new()
593 /// .file("src/foo.c")
594 /// .includes(extra_dir)
595 /// .compile("foo");
596 /// ```
597 pub fn includes<P>(&mut self, dirs: P) -> &mut Build
598 where
599 P: IntoIterator,
600 P::Item: AsRef<Path>,
601 {
602 for dir in dirs {
603 self.include(dir);
604 }
605 self
606 }
607
608 /// Specify a `-D` variable with an optional value.
609 ///
610 /// # Example
611 ///
612 /// ```no_run
613 /// cc::Build::new()
614 /// .file("src/foo.c")
615 /// .define("FOO", "BAR")
616 /// .define("BAZ", None)
617 /// .compile("foo");
618 /// ```
619 pub fn define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build {
620 self.definitions
621 .push((var.into(), val.into().map(Into::into)));
622 self
623 }
624
625 /// Add an arbitrary object file to link in
626 pub fn object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build {
627 self.objects.push(obj.as_ref().into());
628 self
629 }
630
631 /// Add arbitrary object files to link in
632 pub fn objects<P>(&mut self, objs: P) -> &mut Build
633 where
634 P: IntoIterator,
635 P::Item: AsRef<Path>,
636 {
637 for obj in objs {
638 self.object(obj);
639 }
640 self
641 }
642
643 /// Add an arbitrary flag to the invocation of the compiler
644 ///
645 /// # Example
646 ///
647 /// ```no_run
648 /// cc::Build::new()
649 /// .file("src/foo.c")
650 /// .flag("-ffunction-sections")
651 /// .compile("foo");
652 /// ```
653 pub fn flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
654 self.flags.push(flag.as_ref().into());
655 self
656 }
657
658 /// Add multiple flags to the invocation of the compiler.
659 /// This is equivalent to calling [`flag`](Self::flag) for each item in the iterator.
660 ///
661 /// # Example
662 /// ```no_run
663 /// cc::Build::new()
664 /// .file("src/foo.c")
665 /// .flags(["-Wall", "-Wextra"])
666 /// .compile("foo");
667 /// ```
668 pub fn flags<Iter>(&mut self, flags: Iter) -> &mut Build
669 where
670 Iter: IntoIterator,
671 Iter::Item: AsRef<OsStr>,
672 {
673 for flag in flags {
674 self.flag(flag);
675 }
676 self
677 }
678
679 /// Removes a compiler flag that was added by [`Build::flag`].
680 ///
681 /// Will not remove flags added by other means (default flags,
682 /// flags from env, and so on).
683 ///
684 /// # Example
685 /// ```
686 /// cc::Build::new()
687 /// .file("src/foo.c")
688 /// .flag("unwanted_flag")
689 /// .remove_flag("unwanted_flag");
690 /// ```
691 pub fn remove_flag(&mut self, flag: &str) -> &mut Build {
692 self.flags.retain(|other_flag| &**other_flag != flag);
693 self
694 }
695
696 /// Add a flag to the invocation of the ar
697 ///
698 /// # Example
699 ///
700 /// ```no_run
701 /// cc::Build::new()
702 /// .file("src/foo.c")
703 /// .file("src/bar.c")
704 /// .ar_flag("/NODEFAULTLIB:libc.dll")
705 /// .compile("foo");
706 /// ```
707 pub fn ar_flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
708 self.ar_flags.push(flag.as_ref().into());
709 self
710 }
711
712 /// Add a flag that will only be used with assembly files.
713 ///
714 /// The flag will be applied to input files with either a `.s` or
715 /// `.asm` extension (case insensitive).
716 ///
717 /// # Example
718 ///
719 /// ```no_run
720 /// cc::Build::new()
721 /// .asm_flag("-Wa,-defsym,abc=1")
722 /// .file("src/foo.S") // The asm flag will be applied here
723 /// .file("src/bar.c") // The asm flag will not be applied here
724 /// .compile("foo");
725 /// ```
726 pub fn asm_flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
727 self.asm_flags.push(flag.as_ref().into());
728 self
729 }
730
731 /// Add an arbitrary flag to the invocation of the compiler if it supports it
732 ///
733 /// # Example
734 ///
735 /// ```no_run
736 /// cc::Build::new()
737 /// .file("src/foo.c")
738 /// .flag_if_supported("-Wlogical-op") // only supported by GCC
739 /// .flag_if_supported("-Wunreachable-code") // only supported by clang
740 /// .compile("foo");
741 /// ```
742 pub fn flag_if_supported(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
743 self.flags_supported.push(flag.as_ref().into());
744 self
745 }
746
747 /// Add flags from the specified environment variable.
748 ///
749 /// Normally the `cc` crate will consult with the standard set of environment
750 /// variables (such as `CFLAGS` and `CXXFLAGS`) to construct the compiler invocation. Use of
751 /// this method provides additional levers for the end user to use when configuring the build
752 /// process.
753 ///
754 /// Just like the standard variables, this method will search for an environment variable with
755 /// appropriate target prefixes, when appropriate.
756 ///
757 /// # Examples
758 ///
759 /// This method is particularly beneficial in introducing the ability to specify crate-specific
760 /// flags.
761 ///
762 /// ```no_run
763 /// cc::Build::new()
764 /// .file("src/foo.c")
765 /// .try_flags_from_environment(concat!(env!("CARGO_PKG_NAME"), "_CFLAGS"))
766 /// .expect("the environment variable must be specified and UTF-8")
767 /// .compile("foo");
768 /// ```
769 ///
770 pub fn try_flags_from_environment(&mut self, environ_key: &str) -> Result<&mut Build, Error> {
771 let flags = self.envflags(environ_key)?.ok_or_else(|| {
772 Error::new(
773 ErrorKind::EnvVarNotFound,
774 format!("could not find environment variable {environ_key}"),
775 )
776 })?;
777 self.flags.extend(
778 flags
779 .into_iter()
780 .map(|flag| Arc::from(OsString::from(flag).as_os_str())),
781 );
782 Ok(self)
783 }
784
785 /// Set the `-shared` flag.
786 ///
787 /// This will typically be ignored by the compiler when calling [`Self::compile()`] since it only
788 /// produces static libraries.
789 ///
790 /// # Example
791 ///
792 /// ```no_run
793 /// // This will create a library named "liblibfoo.so.a"
794 /// cc::Build::new()
795 /// .file("src/foo.c")
796 /// .shared_flag(true)
797 /// .compile("libfoo.so");
798 /// ```
799 #[deprecated = "cc only creates static libraries, setting this does nothing"]
800 pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build {
801 self.shared_flag = Some(shared_flag);
802 self
803 }
804
805 /// Set the `-static` flag.
806 ///
807 /// This will typically be ignored by the compiler when calling [`Self::compile()`] since it only
808 /// produces static libraries.
809 ///
810 /// # Example
811 ///
812 /// ```no_run
813 /// cc::Build::new()
814 /// .file("src/foo.c")
815 /// .shared_flag(true)
816 /// .static_flag(true)
817 /// .compile("foo");
818 /// ```
819 #[deprecated = "cc only creates static libraries, setting this does nothing"]
820 pub fn static_flag(&mut self, static_flag: bool) -> &mut Build {
821 self.static_flag = Some(static_flag);
822 self
823 }
824
825 /// Disables the generation of default compiler flags. The default compiler
826 /// flags may cause conflicts in some cross compiling scenarios.
827 ///
828 /// Setting the `CRATE_CC_NO_DEFAULTS` environment variable has the same
829 /// effect as setting this to `true`. The presence of the environment
830 /// variable and the value of `no_default_flags` will be OR'd together.
831 pub fn no_default_flags(&mut self, no_default_flags: bool) -> &mut Build {
832 self.no_default_flags = no_default_flags;
833 self
834 }
835
836 /// Add a file which will be compiled
837 pub fn file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build {
838 self.files.push(p.as_ref().into());
839 self
840 }
841
842 /// Add files which will be compiled
843 pub fn files<P>(&mut self, p: P) -> &mut Build
844 where
845 P: IntoIterator,
846 P::Item: AsRef<Path>,
847 {
848 for file in p.into_iter() {
849 self.file(file);
850 }
851 self
852 }
853
854 /// Get the files which will be compiled
855 pub fn get_files(&self) -> impl Iterator<Item = &Path> {
856 self.files.iter().map(AsRef::as_ref)
857 }
858
859 /// Set C++ support.
860 ///
861 /// The other `cpp_*` options will only become active if this is set to
862 /// `true`.
863 ///
864 /// The name of the C++ standard library to link is decided by:
865 /// 1. If [`cpp_link_stdlib`](Build::cpp_link_stdlib) is set, use its value.
866 /// 2. Else if the `CXXSTDLIB` environment variable is set, use its value.
867 /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
868 /// `None` for MSVC and `stdc++` for anything else.
869 pub fn cpp(&mut self, cpp: bool) -> &mut Build {
870 self.cpp = cpp;
871 self
872 }
873
874 /// Set CUDA C++ support.
875 ///
876 /// Enabling CUDA will invoke the CUDA compiler, NVCC. While NVCC accepts
877 /// the most common compiler flags, e.g. `-std=c++17`, some project-specific
878 /// flags might have to be prefixed with "-Xcompiler" flag, for example as
879 /// `.flag("-Xcompiler").flag("-fpermissive")`. See the documentation for
880 /// `nvcc`, the CUDA compiler driver, at <https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/>
881 /// for more information.
882 ///
883 /// If enabled, this also implicitly enables C++ support.
884 pub fn cuda(&mut self, cuda: bool) -> &mut Build {
885 self.cuda = cuda;
886 if cuda {
887 self.cpp = true;
888 self.cudart = Some("static".into());
889 }
890 self
891 }
892
893 /// Link CUDA run-time.
894 ///
895 /// This option mimics the `--cudart` NVCC command-line option. Just like
896 /// the original it accepts `{none|shared|static}`, with default being
897 /// `static`. The method has to be invoked after `.cuda(true)`, or not
898 /// at all, if the default is right for the project.
899 pub fn cudart(&mut self, cudart: &str) -> &mut Build {
900 if self.cuda {
901 self.cudart = Some(cudart.into());
902 }
903 self
904 }
905
906 /// Set CUDA host compiler.
907 ///
908 /// By default, a `-ccbin` flag will be passed to NVCC to specify the
909 /// underlying host compiler. The value of `-ccbin` is the same as the
910 /// chosen C++ compiler. This is not always desired, because NVCC might
911 /// not support that compiler. In this case, you can remove the `-ccbin`
912 /// flag so that NVCC will choose the host compiler by itself.
913 pub fn ccbin(&mut self, ccbin: bool) -> &mut Build {
914 self.ccbin = ccbin;
915 self
916 }
917
918 /// Specify the C or C++ language standard version.
919 ///
920 /// These values are common to modern versions of GCC, Clang and MSVC:
921 /// - `c11` for ISO/IEC 9899:2011
922 /// - `c17` for ISO/IEC 9899:2018
923 /// - `c++14` for ISO/IEC 14882:2014
924 /// - `c++17` for ISO/IEC 14882:2017
925 /// - `c++20` for ISO/IEC 14882:2020
926 ///
927 /// Other values have less broad support, e.g. MSVC does not support `c++11`
928 /// (`c++14` is the minimum), `c89` (omit the flag instead) or `c99`.
929 ///
930 /// For compiling C++ code, you should also set `.cpp(true)`.
931 ///
932 /// The default is that no standard flag is passed to the compiler, so the
933 /// language version will be the compiler's default.
934 ///
935 /// # Example
936 ///
937 /// ```no_run
938 /// cc::Build::new()
939 /// .file("src/modern.cpp")
940 /// .cpp(true)
941 /// .std("c++17")
942 /// .compile("modern");
943 /// ```
944 pub fn std(&mut self, std: &str) -> &mut Build {
945 self.std = Some(std.into());
946 self
947 }
948
949 /// Set warnings into errors flag.
950 ///
951 /// Disabled by default.
952 ///
953 /// Warning: turning warnings into errors only make sense
954 /// if you are a developer of the crate using cc-rs.
955 /// Some warnings only appear on some architecture or
956 /// specific version of the compiler. Any user of this crate,
957 /// or any other crate depending on it, could fail during
958 /// compile time.
959 ///
960 /// # Example
961 ///
962 /// ```no_run
963 /// cc::Build::new()
964 /// .file("src/foo.c")
965 /// .warnings_into_errors(true)
966 /// .compile("libfoo.a");
967 /// ```
968 pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build {
969 self.warnings_into_errors = warnings_into_errors;
970 self
971 }
972
973 /// Set warnings flags.
974 ///
975 /// Adds some flags:
976 /// - "-Wall" for MSVC.
977 /// - "-Wall", "-Wextra" for GNU and Clang.
978 ///
979 /// Enabled by default.
980 ///
981 /// # Example
982 ///
983 /// ```no_run
984 /// cc::Build::new()
985 /// .file("src/foo.c")
986 /// .warnings(false)
987 /// .compile("libfoo.a");
988 /// ```
989 pub fn warnings(&mut self, warnings: bool) -> &mut Build {
990 self.warnings = Some(warnings);
991 self.extra_warnings = Some(warnings);
992 self
993 }
994
995 /// Set extra warnings flags.
996 ///
997 /// Adds some flags:
998 /// - nothing for MSVC.
999 /// - "-Wextra" for GNU and Clang.
1000 ///
1001 /// Enabled by default.
1002 ///
1003 /// # Example
1004 ///
1005 /// ```no_run
1006 /// // Disables -Wextra, -Wall remains enabled:
1007 /// cc::Build::new()
1008 /// .file("src/foo.c")
1009 /// .extra_warnings(false)
1010 /// .compile("libfoo.a");
1011 /// ```
1012 pub fn extra_warnings(&mut self, warnings: bool) -> &mut Build {
1013 self.extra_warnings = Some(warnings);
1014 self
1015 }
1016
1017 /// Set the standard library to link against when compiling with C++
1018 /// support.
1019 ///
1020 /// If the `CXXSTDLIB` environment variable is set, its value will
1021 /// override the default value, but not the value explicitly set by calling
1022 /// this function.
1023 ///
1024 /// A value of `None` indicates that no automatic linking should happen,
1025 /// otherwise cargo will link against the specified library.
1026 ///
1027 /// The given library name must not contain the `lib` prefix.
1028 ///
1029 /// Common values:
1030 /// - `stdc++` for GNU
1031 /// - `c++` for Clang
1032 /// - `c++_shared` or `c++_static` for Android
1033 ///
1034 /// # Example
1035 ///
1036 /// ```no_run
1037 /// cc::Build::new()
1038 /// .file("src/foo.c")
1039 /// .shared_flag(true)
1040 /// .cpp_link_stdlib("stdc++")
1041 /// .compile("libfoo.so");
1042 /// ```
1043 pub fn cpp_link_stdlib<'a, V: Into<Option<&'a str>>>(
1044 &mut self,
1045 cpp_link_stdlib: V,
1046 ) -> &mut Build {
1047 self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(Arc::from));
1048 self
1049 }
1050
1051 /// Force linker to statically link C++ stdlib. By default cc-rs will emit
1052 /// rustc-link flag to link against system C++ stdlib (e.g. libstdc++.so, libc++.so)
1053 /// Provide value of `true` if linking against system library is not desired
1054 ///
1055 /// Note that for `wasm32` target C++ stdlib will always be linked statically
1056 ///
1057 /// # Example
1058 ///
1059 /// ```no_run
1060 /// cc::Build::new()
1061 /// .file("src/foo.cpp")
1062 /// .cpp(true)
1063 /// .cpp_link_stdlib("stdc++")
1064 /// .cpp_link_stdlib_static(true)
1065 /// .compile("foo");
1066 /// ```
1067 pub fn cpp_link_stdlib_static(&mut self, is_static: bool) -> &mut Build {
1068 self.cpp_link_stdlib_static = is_static;
1069 self
1070 }
1071
1072 /// Force the C++ compiler to use the specified standard library.
1073 ///
1074 /// Setting this option will automatically set `cpp_link_stdlib` to the same
1075 /// value.
1076 ///
1077 /// The default value of this option is always `None`.
1078 ///
1079 /// This option has no effect when compiling for a Visual Studio based
1080 /// target.
1081 ///
1082 /// This option sets the `-stdlib` flag, which is only supported by some
1083 /// compilers (clang, icc) but not by others (gcc). The library will not
1084 /// detect which compiler is used, as such it is the responsibility of the
1085 /// caller to ensure that this option is only used in conjunction with a
1086 /// compiler which supports the `-stdlib` flag.
1087 ///
1088 /// A value of `None` indicates that no specific C++ standard library should
1089 /// be used, otherwise `-stdlib` is added to the compile invocation.
1090 ///
1091 /// The given library name must not contain the `lib` prefix.
1092 ///
1093 /// Common values:
1094 /// - `stdc++` for GNU
1095 /// - `c++` for Clang
1096 ///
1097 /// # Example
1098 ///
1099 /// ```no_run
1100 /// cc::Build::new()
1101 /// .file("src/foo.c")
1102 /// .cpp_set_stdlib("c++")
1103 /// .compile("libfoo.a");
1104 /// ```
1105 pub fn cpp_set_stdlib<'a, V: Into<Option<&'a str>>>(
1106 &mut self,
1107 cpp_set_stdlib: V,
1108 ) -> &mut Build {
1109 let cpp_set_stdlib = cpp_set_stdlib.into().map(Arc::from);
1110 self.cpp_set_stdlib.clone_from(&cpp_set_stdlib);
1111 self.cpp_link_stdlib = Some(cpp_set_stdlib);
1112 self
1113 }
1114
1115 /// Configures the `rustc` target this configuration will be compiling
1116 /// for.
1117 ///
1118 /// This will fail if using a target not in a pre-compiled list taken from
1119 /// `rustc +nightly --print target-list`. The list will be updated
1120 /// periodically.
1121 ///
1122 /// You should avoid setting this in build scripts, target information
1123 /// will instead be retrieved from the environment variables `TARGET` and
1124 /// `CARGO_CFG_TARGET_*` that Cargo sets.
1125 ///
1126 /// # Example
1127 ///
1128 /// ```no_run
1129 /// cc::Build::new()
1130 /// .file("src/foo.c")
1131 /// .target("aarch64-linux-android")
1132 /// .compile("foo");
1133 /// ```
1134 pub fn target(&mut self, target: &str) -> &mut Build {
1135 self.target = Some(target.into());
1136 self
1137 }
1138
1139 /// Configures the host assumed by this configuration.
1140 ///
1141 /// This option is automatically scraped from the `HOST` environment
1142 /// variable by build scripts, so it's not required to call this function.
1143 ///
1144 /// # Example
1145 ///
1146 /// ```no_run
1147 /// cc::Build::new()
1148 /// .file("src/foo.c")
1149 /// .host("arm-linux-gnueabihf")
1150 /// .compile("foo");
1151 /// ```
1152 pub fn host(&mut self, host: &str) -> &mut Build {
1153 self.host = Some(host.into());
1154 self
1155 }
1156
1157 /// Configures the optimization level of the generated object files.
1158 ///
1159 /// This option is automatically scraped from the `OPT_LEVEL` environment
1160 /// variable by build scripts, so it's not required to call this function.
1161 pub fn opt_level(&mut self, opt_level: u32) -> &mut Build {
1162 self.opt_level = Some(opt_level.to_string().into());
1163 self
1164 }
1165
1166 /// Configures the optimization level of the generated object files.
1167 ///
1168 /// This option is automatically scraped from the `OPT_LEVEL` environment
1169 /// variable by build scripts, so it's not required to call this function.
1170 pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build {
1171 self.opt_level = Some(opt_level.into());
1172 self
1173 }
1174
1175 /// Configures whether the compiler will emit debug information when
1176 /// generating object files.
1177 ///
1178 /// This option is automatically scraped from the `DEBUG` environment
1179 /// variable by build scripts, so it's not required to call this function.
1180 pub fn debug(&mut self, debug: bool) -> &mut Build {
1181 self.debug = Some(debug.to_string().into());
1182 self
1183 }
1184
1185 /// Configures whether the compiler will emit debug information when
1186 /// generating object files.
1187 ///
1188 /// This should be one of the values accepted by Cargo's [`debug`][1]
1189 /// profile setting, which cc-rs will try to map to the appropriate C
1190 /// compiler flag.
1191 ///
1192 /// This option is automatically scraped from the `DEBUG` environment
1193 /// variable by build scripts, so it's not required to call this function.
1194 ///
1195 /// [1]: https://doc.rust-lang.org/cargo/reference/profiles.html#debug
1196 pub fn debug_str(&mut self, debug: &str) -> &mut Build {
1197 self.debug = Some(debug.into());
1198 self
1199 }
1200
1201 /// Configures whether the compiler will emit instructions to store
1202 /// frame pointers during codegen.
1203 ///
1204 /// This option is automatically enabled when debug information is emitted.
1205 /// Otherwise the target platform compiler's default will be used.
1206 /// You can use this option to force a specific setting.
1207 pub fn force_frame_pointer(&mut self, force: bool) -> &mut Build {
1208 self.force_frame_pointer = Some(force);
1209 self
1210 }
1211
1212 /// Configures the output directory where all object files and static
1213 /// libraries will be located.
1214 ///
1215 /// This option is automatically scraped from the `OUT_DIR` environment
1216 /// variable by build scripts, so it's not required to call this function.
1217 pub fn out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build {
1218 self.out_dir = Some(out_dir.as_ref().into());
1219 self
1220 }
1221
1222 /// Configures the compiler to be used to produce output.
1223 ///
1224 /// This option is automatically determined from the target platform or a
1225 /// number of environment variables, so it's not required to call this
1226 /// function.
1227 pub fn compiler<P: AsRef<Path>>(&mut self, compiler: P) -> &mut Build {
1228 self.compiler = Some(compiler.as_ref().into());
1229 self
1230 }
1231
1232 /// Configures the tool used to assemble archives.
1233 ///
1234 /// This option is automatically determined from the target platform or a
1235 /// number of environment variables, so it's not required to call this
1236 /// function.
1237 pub fn archiver<P: AsRef<Path>>(&mut self, archiver: P) -> &mut Build {
1238 self.archiver = Some(archiver.as_ref().into());
1239 self
1240 }
1241
1242 /// Configures the tool used to index archives.
1243 ///
1244 /// This option is automatically determined from the target platform or a
1245 /// number of environment variables, so it's not required to call this
1246 /// function.
1247 pub fn ranlib<P: AsRef<Path>>(&mut self, ranlib: P) -> &mut Build {
1248 self.ranlib = Some(ranlib.as_ref().into());
1249 self
1250 }
1251
1252 /// Define whether metadata should be emitted for cargo allowing it to
1253 /// automatically link the binary. Defaults to `true`.
1254 ///
1255 /// The emitted metadata is:
1256 ///
1257 /// - `rustc-link-lib=static=`*compiled lib*
1258 /// - `rustc-link-search=native=`*target folder*
1259 /// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=`
1260 /// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib`
1261 /// - If `emit_rerun_if_env_changed` is not `false`, `rerun-if-env-changed=`*env*
1262 ///
1263 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build {
1264 self.cargo_output.metadata = cargo_metadata;
1265 self
1266 }
1267
1268 /// Define whether compile warnings should be emitted for cargo. Defaults to
1269 /// `true`.
1270 ///
1271 /// If disabled, compiler messages will not be printed.
1272 /// Issues unrelated to the compilation will always produce cargo warnings regardless of this setting.
1273 pub fn cargo_warnings(&mut self, cargo_warnings: bool) -> &mut Build {
1274 self.cargo_output.warnings = cargo_warnings;
1275 self
1276 }
1277
1278 /// Define whether debug information should be emitted for cargo. Defaults to whether
1279 /// or not the environment variable `CC_ENABLE_DEBUG_OUTPUT` is set.
1280 ///
1281 /// If enabled, the compiler will emit debug information when generating object files,
1282 /// such as the command invoked and the exit status.
1283 pub fn cargo_debug(&mut self, cargo_debug: bool) -> &mut Build {
1284 self.cargo_output.debug = cargo_debug;
1285 self
1286 }
1287
1288 /// Define whether compiler output (to stdout) should be emitted. Defaults to `true`
1289 /// (forward compiler stdout to this process' stdout)
1290 ///
1291 /// Some compilers emit errors to stdout, so if you *really* need stdout to be clean
1292 /// you should also set this to `false`.
1293 pub fn cargo_output(&mut self, cargo_output: bool) -> &mut Build {
1294 self.cargo_output.output = if cargo_output {
1295 OutputKind::Forward
1296 } else {
1297 OutputKind::Discard
1298 };
1299 self
1300 }
1301
1302 /// Adds a native library modifier that will be added to the
1303 /// `rustc-link-lib=static:MODIFIERS=LIBRARY_NAME` metadata line
1304 /// emitted for cargo if `cargo_metadata` is enabled.
1305 /// See <https://doc.rust-lang.org/rustc/command-line-arguments.html#-l-link-the-generated-crate-to-a-native-library>
1306 /// for the list of modifiers accepted by rustc.
1307 pub fn link_lib_modifier(&mut self, link_lib_modifier: impl AsRef<OsStr>) -> &mut Build {
1308 self.link_lib_modifiers
1309 .push(link_lib_modifier.as_ref().into());
1310 self
1311 }
1312
1313 /// Configures whether the compiler will emit position independent code.
1314 ///
1315 /// This option defaults to `false` for `windows-gnu` and bare metal targets and
1316 /// to `true` for all other targets.
1317 pub fn pic(&mut self, pic: bool) -> &mut Build {
1318 self.pic = Some(pic);
1319 self
1320 }
1321
1322 /// Configures whether the Procedure Linkage Table is used for indirect
1323 /// calls into shared libraries.
1324 ///
1325 /// The PLT is used to provide features like lazy binding, but introduces
1326 /// a small performance loss due to extra pointer indirection. Setting
1327 /// `use_plt` to `false` can provide a small performance increase.
1328 ///
1329 /// Note that skipping the PLT requires a recent version of GCC/Clang.
1330 ///
1331 /// This only applies to ELF targets. It has no effect on other platforms.
1332 pub fn use_plt(&mut self, use_plt: bool) -> &mut Build {
1333 self.use_plt = Some(use_plt);
1334 self
1335 }
1336
1337 /// Define whether metadata should be emitted for cargo to only trigger
1338 /// rebuild when detected environment changes, by default build script is
1339 /// always run on every compilation if no rerun cargo metadata is emitted.
1340 ///
1341 /// NOTE that cc does not emit metadata to detect changes for `PATH`, since it could
1342 /// be changed every compilation yet does not affect the result of compilation
1343 /// (i.e. rust-analyzer adds temporary directory to `PATH`).
1344 ///
1345 /// cc in general, has no way detecting changes to compiler, as there are so many ways to
1346 /// change it and sidestep the detection, for example the compiler might be wrapped in a script
1347 /// so detecting change of the file, or using checksum won't work.
1348 ///
1349 /// We recommend users to decide for themselves, if they want rebuild if the compiler has been upgraded
1350 /// or changed, and how to detect that.
1351 ///
1352 /// This has no effect if the `cargo_metadata` option is `false`.
1353 ///
1354 /// This option defaults to `true`.
1355 pub fn emit_rerun_if_env_changed(&mut self, emit_rerun_if_env_changed: bool) -> &mut Build {
1356 self.emit_rerun_if_env_changed = emit_rerun_if_env_changed;
1357 self
1358 }
1359
1360 /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools.
1361 ///
1362 /// This option defaults to `false`, and affect only msvc targets.
1363 pub fn static_crt(&mut self, static_crt: bool) -> &mut Build {
1364 self.static_crt = Some(static_crt);
1365 self
1366 }
1367
1368 /// Configure whether *FLAGS variables are parsed using `shlex`, similarly to `make` and
1369 /// `cmake`.
1370 ///
1371 /// This option defaults to `false`.
1372 pub fn shell_escaped_flags(&mut self, shell_escaped_flags: bool) -> &mut Build {
1373 self.shell_escaped_flags = Some(shell_escaped_flags);
1374 self
1375 }
1376
1377 /// Configure whether cc should automatically inherit compatible flags passed to rustc
1378 /// from `CARGO_ENCODED_RUSTFLAGS`.
1379 ///
1380 /// This option defaults to `true`.
1381 pub fn inherit_rustflags(&mut self, inherit_rustflags: bool) -> &mut Build {
1382 self.inherit_rustflags = inherit_rustflags;
1383 self
1384 }
1385
1386 /// Configure whether cc should automatically inherit path remap rules
1387 /// from cargo's [`trim-paths`] profile setting,
1388 /// and translate them into `-fmacro-prefix-map`/ `-fdebug-prefix-map` flags.
1389 ///
1390 /// This option defaults to `true`.
1391 ///
1392 /// This option doesn't support Windows MSVC cl.exe yet.
1393 /// Only clang and GCC are supported.
1394 ///
1395 /// <div class="warning">
1396 ///
1397 /// [`trim-paths`] is currently an unstable cargo feature,
1398 /// only available on nightly with `-Ztrim-paths`.
1399 /// The contract around this option may change as the cargo feature evolves.
1400 ///
1401 /// </div>
1402 ///
1403 /// [`trim-paths`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#profile-trim-paths-option
1404 pub fn inherit_trim_paths(&mut self, inherit_trim_paths: bool) -> &mut Build {
1405 self.inherit_trim_paths = inherit_trim_paths;
1406 self
1407 }
1408
1409 /// Prefer to use clang-cl over msvc.
1410 ///
1411 /// This option defaults to `false`.
1412 pub fn prefer_clang_cl_over_msvc(&mut self, prefer_clang_cl_over_msvc: bool) -> &mut Build {
1413 self.prefer_clang_cl_over_msvc = prefer_clang_cl_over_msvc;
1414 self
1415 }
1416
1417 /// Set an environment variable for compiler invocations and other child processes.
1418 ///
1419 /// `cc` reads a lot of different variables from the current process' environment. It currently
1420 /// allows the following standard environment variables to be overwritten by this function:
1421 /// - `SDKROOT`
1422 /// - `*_DEPLOYMENT_TARGET`
1423 /// - `WASI_SDK_ROOT`
1424 ///
1425 /// The logic here is "environment variables that the C compiler could itself reasonably have
1426 /// read".
1427 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Build
1428 where
1429 K: AsRef<OsStr>,
1430 V: AsRef<OsStr>,
1431 {
1432 self.env.push((key.as_ref().into(), val.as_ref().into()));
1433 self
1434 }
1435
1436 // retained for backwards compatibility only
1437 #[doc(hidden)]
1438 #[deprecated = "use `env` instead"]
1439 pub fn __set_env<K, V>(&mut self, key: K, val: V) -> &mut Build
1440 where
1441 K: AsRef<OsStr>,
1442 V: AsRef<OsStr>,
1443 {
1444 self.env(key, val)
1445 }
1446}
1447
1448/// Invoke or fetch the compiler or archiver.
1449impl Build {
1450 /// Run the compiler to test if it accepts the given flag.
1451 ///
1452 /// For a convenience method for setting flags conditionally,
1453 /// see `flag_if_supported()`.
1454 ///
1455 /// It may return error if it's unable to run the compiler with a test file
1456 /// (e.g. the compiler is missing or a write to the `out_dir` failed).
1457 ///
1458 /// Note: Once computed, the result of this call is stored in the
1459 /// `known_flag_support` field. If `is_flag_supported(flag)`
1460 /// is called again, the result will be read from the hash table.
1461 pub fn is_flag_supported(&self, flag: impl AsRef<OsStr>) -> Result<bool, Error> {
1462 self.is_flag_supported_inner(
1463 flag.as_ref(),
1464 &self.get_base_compiler()?,
1465 &self.get_target()?,
1466 )
1467 }
1468
1469 fn ensure_check_file(&self) -> Result<PathBuf, Error> {
1470 let out_dir = self.get_out_dir()?;
1471 let src = if self.cuda {
1472 assert!(self.cpp);
1473 out_dir.join("flag_check.cu")
1474 } else if self.cpp {
1475 out_dir.join("flag_check.cpp")
1476 } else {
1477 out_dir.join("flag_check.c")
1478 };
1479
1480 if !src.exists() {
1481 let mut f = fs::File::create(&src)?;
1482 write!(f, "int main(void) {{ return 0; }}")?;
1483 }
1484
1485 Ok(src)
1486 }
1487
1488 fn is_flag_supported_inner(
1489 &self,
1490 flag: &OsStr,
1491 tool: &Tool,
1492 target: &TargetInfo<'_>,
1493 ) -> Result<bool, Error> {
1494 let compiler_flag = CompilerFlag {
1495 compiler: tool.path().into(),
1496 flag: flag.into(),
1497 };
1498
1499 if let Some(is_supported) = self
1500 .build_cache
1501 .known_flag_support_status_cache
1502 .read()
1503 .unwrap()
1504 .get(&compiler_flag)
1505 .cloned()
1506 {
1507 return Ok(is_supported);
1508 }
1509
1510 let out_dir = self.get_out_dir()?;
1511 let src = self.ensure_check_file()?;
1512 let obj = out_dir.join("flag_check");
1513
1514 let mut compiler = {
1515 let mut cfg = Build::new();
1516 cfg.flag(flag)
1517 .compiler(tool.path())
1518 .cargo_metadata(self.cargo_output.metadata)
1519 .opt_level(0)
1520 .debug(false)
1521 .cpp(self.cpp)
1522 .cuda(self.cuda)
1523 .out_dir(&out_dir)
1524 .inherit_rustflags(false)
1525 .inherit_trim_paths(false)
1526 .emit_rerun_if_env_changed(self.emit_rerun_if_env_changed);
1527 // The probe has to see the environment the compiler is invoked in,
1528 // or it answers a question about a different compiler than the one
1529 // being built with: a bare compiler name resolves through this
1530 // `PATH`, not the ambient one. Also share the caches, so that a
1531 // compiler family already worked out is not worked out again.
1532 cfg.env.clone_from(&self.env);
1533 cfg.build_cache = Arc::clone(&self.build_cache);
1534 if let Some(target) = &self.target {
1535 cfg.target(target);
1536 }
1537 if let Some(host) = &self.host {
1538 cfg.host(host);
1539 }
1540 cfg.try_get_compiler()?
1541 };
1542
1543 // Clang uses stderr for verbose output, which yields a false positive
1544 // result if the CFLAGS/CXXFLAGS include -v to aid in debugging.
1545 if compiler.family.verbose_stderr() {
1546 compiler.remove_arg("-v".into());
1547 }
1548 if compiler.is_like_clang() {
1549 // Avoid reporting that the arg is unsupported just because the
1550 // compiler complains that it wasn't used.
1551 compiler.push_cc_arg("-Wno-unused-command-line-argument".into());
1552 }
1553
1554 let mut cmd = compiler.to_command();
1555 cmd.set_flag_supported_env(&self.env);
1556 command_add_output_file(
1557 &mut cmd,
1558 &obj,
1559 CmdAddOutputFileArgs {
1560 cuda: self.cuda,
1561 is_assembler_msvc: false,
1562 msvc: compiler.is_like_msvc(),
1563 clang: compiler.is_like_clang(),
1564 gnu: compiler.is_like_gnu(),
1565 is_asm: false,
1566 is_arm: is_arm(target),
1567 },
1568 );
1569
1570 // Checking for compiler flags does not require linking (and we _must_
1571 // avoid making it do so, since it breaks cross-compilation when the C
1572 // compiler isn't configured to be able to link).
1573 // https://github.com/rust-lang/cc-rs/issues/1423
1574 cmd.arg("-c");
1575
1576 if compiler.supports_path_delimiter() {
1577 cmd.arg("--");
1578 }
1579
1580 cmd.arg(&src);
1581
1582 if compiler.is_like_msvc() {
1583 // On MSVC we need to make sure the LIB directory is included
1584 // so the CRT can be found.
1585 for (key, value) in &tool.env {
1586 if key == "LIB" {
1587 cmd.env("LIB", value);
1588 break;
1589 }
1590 }
1591 }
1592
1593 cmd.current_dir(out_dir);
1594 self.cargo_output
1595 .print_debug(&format_args!("running: {cmd:?}"));
1596 let output = cmd.output()?;
1597 let is_supported = output.status.success() && output.stderr.is_empty();
1598
1599 self.build_cache
1600 .known_flag_support_status_cache
1601 .write()
1602 .unwrap()
1603 .insert(compiler_flag, is_supported);
1604
1605 Ok(is_supported)
1606 }
1607
1608 /// Run the compiler, generating the file `output`
1609 ///
1610 /// This will return a result instead of panicking; see [`Self::compile()`] for
1611 /// the complete description.
1612 pub fn try_compile(&self, output: &str) -> Result<(), Error> {
1613 let mut output_components = Path::new(output).components();
1614 match (output_components.next(), output_components.next()) {
1615 (Some(Component::Normal(_)), None) => {}
1616 _ => {
1617 return Err(Error::new(
1618 ErrorKind::InvalidArgument,
1619 "argument of `compile` must be a single normal path component",
1620 ));
1621 }
1622 }
1623
1624 let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
1625 (&output[3..output.len() - 2], output.to_owned())
1626 } else {
1627 let mut gnu = String::with_capacity(5 + output.len());
1628 gnu.push_str("lib");
1629 gnu.push_str(output);
1630 gnu.push_str(".a");
1631 (output, gnu)
1632 };
1633 let dst = self.get_out_dir()?;
1634
1635 let objects = objects_from_files(&self.files, &dst)?;
1636
1637 self.compile_objects(&objects)?;
1638 self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;
1639
1640 let target = self.get_target()?;
1641 if target.abi == "pauthtest" {
1642 self.cargo_output.print_warning(
1643 &"cc-rs should not be used with `pauthtest` target: it only builds \
1644 static libraries, while `pauthtest` requires shared objects.",
1645 );
1646 }
1647 if target.env == "msvc" {
1648 let compiler = self.get_base_compiler()?;
1649 let atlmfc_lib = compiler
1650 .env()
1651 .iter()
1652 .find(|&(var, _)| var.as_os_str() == OsStr::new("LIB"))
1653 .and_then(|(_, lib_paths)| {
1654 env::split_paths(lib_paths).find(|path| {
1655 let sub = Path::new("atlmfc/lib");
1656 path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub))
1657 })
1658 });
1659
1660 if let Some(atlmfc_lib) = atlmfc_lib {
1661 self.cargo_output.print_metadata(&format_args!(
1662 "cargo:rustc-link-search=native={}",
1663 atlmfc_lib.display()
1664 ));
1665 }
1666 }
1667
1668 if self.link_lib_modifiers.is_empty() {
1669 self.cargo_output
1670 .print_metadata(&format_args!("cargo:rustc-link-lib=static={lib_name}"));
1671 } else {
1672 self.cargo_output.print_metadata(&format_args!(
1673 "cargo:rustc-link-lib=static:{}={}",
1674 JoinOsStrs {
1675 slice: &self.link_lib_modifiers,
1676 delimiter: ','
1677 },
1678 lib_name
1679 ));
1680 }
1681 self.cargo_output.print_metadata(&format_args!(
1682 "cargo:rustc-link-search=native={}",
1683 dst.display()
1684 ));
1685
1686 // Add specific C++ libraries, if enabled.
1687 if self.cpp {
1688 if let Some(stdlib) = self.get_cpp_link_stdlib()? {
1689 if self.cpp_link_stdlib_static {
1690 self.cargo_output.print_metadata(&format_args!(
1691 "cargo:rustc-link-lib=static={}",
1692 stdlib.display()
1693 ));
1694 } else {
1695 self.cargo_output
1696 .print_metadata(&format_args!("cargo:rustc-link-lib={}", stdlib.display()));
1697 }
1698 }
1699 // Link c++ lib from WASI sysroot
1700 if target.arch == "wasm32" {
1701 if target.os == "wasi" {
1702 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
1703 self.cargo_output.print_metadata(&format_args!(
1704 "cargo:rustc-flags=-L {}/lib/{} -lstatic=c++ -lstatic=c++abi",
1705 Path::new(&wasi_sysroot).display(),
1706 self.get_raw_target()?
1707 ));
1708 }
1709 } else if target.os == "linux" {
1710 let musl_sysroot = self.wasm_musl_sysroot().unwrap();
1711 self.cargo_output.print_metadata(&format_args!(
1712 "cargo:rustc-flags=-L {}/lib -lstatic=c++ -lstatic=c++abi",
1713 Path::new(&musl_sysroot).display(),
1714 ));
1715 }
1716 }
1717 // Pauthtest needs LLVM's libc++, libc++abi provided by the sysroot.
1718 if target.abi == "pauthtest" {
1719 let pauthtest_sysroot = self.pauthtest_sysroot()?;
1720 self.cargo_output.print_metadata(&format_args!(
1721 "cargo:rustc-flags=-L {}/lib -lc++ -lc++abi",
1722 Path::new(&pauthtest_sysroot).display(),
1723 ));
1724 }
1725 }
1726
1727 let cudart = match &self.cudart {
1728 Some(opt) => opt, // {none|shared|static}
1729 None => "none",
1730 };
1731 if cudart != "none" {
1732 if let Some(nvcc) = self.which(&self.get_compiler().path, None) {
1733 // Try to figure out the -L search path. If it fails,
1734 // it's on user to specify one by passing it through
1735 // RUSTFLAGS environment variable.
1736 let mut libtst = false;
1737 let mut libdir = nvcc;
1738 libdir.pop(); // remove 'nvcc'
1739 libdir.push("..");
1740 if cfg!(target_os = "linux") {
1741 libdir.push("targets");
1742 libdir.push(format!("{}-linux", target.arch));
1743 if !libdir.exists() && target.arch == "aarch64" {
1744 libdir.pop();
1745 libdir.push("sbsa-linux");
1746 }
1747 libdir.push("lib");
1748 libtst = true;
1749 } else if cfg!(target_env = "msvc") {
1750 libdir.push("lib");
1751 match target.arch {
1752 "x86_64" => {
1753 libdir.push("x64");
1754 libtst = true;
1755 }
1756 "x86" => {
1757 libdir.push("Win32");
1758 libtst = true;
1759 }
1760 _ => libtst = false,
1761 }
1762 }
1763 if libtst && libdir.is_dir() {
1764 self.cargo_output.print_metadata(&format_args!(
1765 "cargo:rustc-link-search=native={}",
1766 libdir.to_str().unwrap()
1767 ));
1768 }
1769
1770 // And now the -l flag.
1771 let lib = match cudart {
1772 "shared" => "cudart",
1773 "static" => "cudart_static",
1774 bad => panic!("unsupported cudart option: {}", bad),
1775 };
1776 self.cargo_output
1777 .print_metadata(&format_args!("cargo:rustc-link-lib={lib}"));
1778 }
1779 }
1780
1781 Ok(())
1782 }
1783
1784 /// Run the compiler, generating the file `output`
1785 ///
1786 /// # Library name
1787 ///
1788 /// The `output` string argument determines the file name for the compiled
1789 /// library. The Rust compiler will create an assembly named "lib"+output+".a".
1790 /// MSVC will create a file named output+".lib".
1791 ///
1792 /// The choice of `output` is close to arbitrary, but:
1793 ///
1794 /// - must be nonempty,
1795 /// - must not contain a path separator (`/`),
1796 /// - must be unique across all `compile` invocations made by the same build
1797 /// script.
1798 ///
1799 /// If your build script compiles a single source file, the base name of
1800 /// that source file would usually be reasonable:
1801 ///
1802 /// ```no_run
1803 /// cc::Build::new().file("blobstore.c").compile("blobstore");
1804 /// ```
1805 ///
1806 /// Compiling multiple source files, some people use their crate's name, or
1807 /// their crate's name + "-cc".
1808 ///
1809 /// Otherwise, please use your imagination.
1810 ///
1811 /// For backwards compatibility, if `output` starts with "lib" *and* ends
1812 /// with ".a", a second "lib" prefix and ".a" suffix do not get added on,
1813 /// but this usage is deprecated; please omit `lib` and `.a` in the argument
1814 /// that you pass.
1815 ///
1816 /// # Panics
1817 ///
1818 /// Panics if `output` is not formatted correctly or if one of the underlying
1819 /// compiler commands fails. It can also panic if it fails reading file names
1820 /// or creating directories.
1821 pub fn compile(&self, output: &str) {
1822 if let Err(e) = self.try_compile(output) {
1823 fail(&e.message);
1824 }
1825 }
1826
1827 /// Run the compiler, generating intermediate files, but without linking
1828 /// them into an archive file.
1829 ///
1830 /// This will return a list of compiled object files, in the same order
1831 /// as they were passed in as `file`/`files` methods.
1832 pub fn compile_intermediates(&self) -> Vec<PathBuf> {
1833 match self.try_compile_intermediates() {
1834 Ok(v) => v,
1835 Err(e) => fail(&e.message),
1836 }
1837 }
1838
1839 /// Run the compiler, generating intermediate files, but without linking
1840 /// them into an archive file.
1841 ///
1842 /// This will return a result instead of panicking; see `compile_intermediates()` for the complete description.
1843 pub fn try_compile_intermediates(&self) -> Result<Vec<PathBuf>, Error> {
1844 let dst = self.get_out_dir()?;
1845 let objects = objects_from_files(&self.files, &dst)?;
1846
1847 self.compile_objects(&objects)?;
1848
1849 Ok(objects.into_iter().map(|v| v.dst).collect())
1850 }
1851
1852 fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
1853 if self.is_disabled() {
1854 return Err(Error::new(
1855 ErrorKind::Disabled,
1856 "the `cc` crate's functionality has been disabled by the `CC_FORCE_DISABLE` environment variable.",
1857 ));
1858 }
1859
1860 #[cfg(feature = "parallel")]
1861 if objs.len() > 1 {
1862 return parallel::run_commands_in_parallel(
1863 &self.cargo_output,
1864 &mut objs.iter().map(|obj| self.create_compile_object_cmd(obj)),
1865 );
1866 }
1867
1868 for obj in objs {
1869 let mut cmd = self.create_compile_object_cmd(obj)?;
1870 run(&mut cmd, &self.cargo_output)?;
1871 }
1872
1873 Ok(())
1874 }
1875
1876 fn create_compile_object_cmd(&self, obj: &Object) -> Result<Command, Error> {
1877 let asm_ext = AsmFileExt::from_path(&obj.src);
1878 let is_asm = asm_ext.is_some();
1879 let target = self.get_target()?;
1880 let msvc = target.env == "msvc";
1881 let compiler = self.try_get_compiler()?;
1882
1883 let is_assembler_msvc = msvc && asm_ext == Some(AsmFileExt::DotAsm);
1884 let mut cmd = if is_assembler_msvc {
1885 self.msvc_macro_assembler()?
1886 } else {
1887 compiler.to_command()
1888 };
1889 let is_arm = is_arm(&target);
1890 command_add_output_file(
1891 &mut cmd,
1892 &obj.dst,
1893 CmdAddOutputFileArgs {
1894 cuda: self.cuda,
1895 is_assembler_msvc,
1896 msvc: compiler.is_like_msvc(),
1897 clang: compiler.is_like_clang(),
1898 gnu: compiler.is_like_gnu(),
1899 is_asm,
1900 is_arm,
1901 },
1902 );
1903 // armasm and armasm64 don't require -c option
1904 if !is_assembler_msvc || !is_arm {
1905 cmd.arg("-c");
1906 }
1907 if self.cuda && self.cuda_file_count() > 1 {
1908 cmd.arg("--device-c");
1909 }
1910 if is_asm {
1911 cmd.args(self.asm_flags.iter().map(std::ops::Deref::deref));
1912 }
1913
1914 if compiler.supports_path_delimiter() && !is_assembler_msvc {
1915 // #513: For `clang-cl`, separate flags/options from the input file.
1916 // When cross-compiling macOS -> Windows, this avoids interpreting
1917 // common `/Users/...` paths as the `/U` flag and triggering
1918 // `-Wslash-u-filename` warning.
1919 cmd.arg("--");
1920 }
1921 cmd.arg(&obj.src);
1922
1923 if cfg!(target_os = "macos") {
1924 self.fix_env_for_apple_os(&mut cmd)?;
1925 }
1926
1927 Ok(cmd)
1928 }
1929
1930 /// This will return a result instead of panicking; see [`Self::expand()`] for
1931 /// the complete description.
1932 pub fn try_expand(&self) -> Result<Vec<u8>, Error> {
1933 let compiler = self.try_get_compiler()?;
1934 let mut cmd = compiler.to_command();
1935 cmd.arg("-E");
1936
1937 assert!(
1938 self.files.len() <= 1,
1939 "Expand may only be called for a single file"
1940 );
1941
1942 let is_asm = self
1943 .files
1944 .iter()
1945 .map(std::ops::Deref::deref)
1946 .find_map(AsmFileExt::from_path)
1947 .is_some();
1948
1949 if compiler.family == (ToolFamily::Msvc { clang_cl: true }) && !is_asm {
1950 // #513: For `clang-cl`, separate flags/options from the input file.
1951 // When cross-compiling macOS -> Windows, this avoids interpreting
1952 // common `/Users/...` paths as the `/U` flag and triggering
1953 // `-Wslash-u-filename` warning.
1954 cmd.arg("--");
1955 }
1956
1957 cmd.args(self.files.iter().map(std::ops::Deref::deref));
1958
1959 run_output(&mut cmd, &self.cargo_output)
1960 }
1961
1962 /// Run the compiler, returning the macro-expanded version of the input files.
1963 ///
1964 /// This is only relevant for C and C++ files.
1965 ///
1966 /// # Panics
1967 /// Panics if more than one file is present in the config, or if compiler
1968 /// path has an invalid file name.
1969 ///
1970 /// # Example
1971 /// ```no_run
1972 /// let out = cc::Build::new().file("src/foo.c").expand();
1973 /// ```
1974 pub fn expand(&self) -> Vec<u8> {
1975 match self.try_expand() {
1976 Err(e) => fail(&e.message),
1977 Ok(v) => v,
1978 }
1979 }
1980
1981 /// Get the compiler that's in use for this configuration.
1982 ///
1983 /// This function will return a `Tool` which represents the culmination
1984 /// of this configuration at a snapshot in time. The returned compiler can
1985 /// be inspected (e.g. the path, arguments, environment) to forward along to
1986 /// other tools, or the `to_command` method can be used to invoke the
1987 /// compiler itself.
1988 ///
1989 /// This method will take into account all configuration such as debug
1990 /// information, optimization level, include directories, defines, etc.
1991 /// Additionally, the compiler binary in use follows the standard
1992 /// conventions for this path, e.g. looking at the explicitly set compiler,
1993 /// environment variables (a number of which are inspected here), and then
1994 /// falling back to the default configuration.
1995 ///
1996 /// # Panics
1997 ///
1998 /// Panics if an error occurred while determining the architecture.
1999 pub fn get_compiler(&self) -> Tool {
2000 match self.try_get_compiler() {
2001 Ok(tool) => tool,
2002 Err(e) => fail(&e.message),
2003 }
2004 }
2005
2006 /// Get the compiler that's in use for this configuration.
2007 ///
2008 /// This will return a result instead of panicking; see
2009 /// [`get_compiler()`](Self::get_compiler) for the complete description.
2010 pub fn try_get_compiler(&self) -> Result<Tool, Error> {
2011 let opt_level = self.get_opt_level()?;
2012 let target = self.get_target()?;
2013
2014 let mut cmd = self.get_base_compiler()?;
2015
2016 // The flags below are added in roughly the following order:
2017 // 1. Default flags
2018 // - Controlled by `cc-rs`.
2019 // 2. `rustc`-inherited flags
2020 // - Controlled by `rustc`.
2021 // 3. Builder flags
2022 // - Controlled by the developer using `cc-rs` in e.g. their `build.rs`.
2023 // 4. Environment flags
2024 // - Controlled by the end user.
2025 //
2026 // This is important to allow later flags to override previous ones.
2027
2028 // Copied from <https://github.com/rust-lang/rust/blob/5db81020006d2920fc9c62ffc0f4322f90bffa04/compiler/rustc_codegen_ssa/src/back/linker.rs#L27-L38>
2029 //
2030 // Disables non-English messages from localized linkers.
2031 // Such messages may cause issues with text encoding on Windows
2032 // and prevent inspection of msvc output in case of errors, which we occasionally do.
2033 // This should be acceptable because other messages from rustc are in English anyway,
2034 // and may also be desirable to improve searchability of the compiler diagnostics.
2035 if matches!(cmd.family, ToolFamily::Msvc { clang_cl: false }) {
2036 cmd.env.push(("VSLANG".into(), "1033".into()));
2037 } else {
2038 cmd.env.push(("LC_ALL".into(), "C".into()));
2039 }
2040
2041 // Disable default flag generation via `no_default_flags` or environment variable
2042 let no_defaults = self.no_default_flags || self.get_env_boolean("CRATE_CC_NO_DEFAULTS");
2043 if !no_defaults {
2044 self.add_default_flags(&mut cmd, &target, &opt_level)?;
2045 }
2046
2047 // Specify various flags that are not considered part of the default flags above.
2048 // FIXME(madsmtm): Should these be considered part of the defaults? If no, why not?
2049 if let Some(ref std) = self.std {
2050 let separator = match cmd.family {
2051 ToolFamily::Msvc { .. } => ':',
2052 ToolFamily::Gnu | ToolFamily::Clang { .. } => '=',
2053 };
2054 cmd.push_cc_arg(format!("-std{separator}{std}").into());
2055 }
2056 for directory in self.include_directories.iter() {
2057 cmd.args.push("-I".into());
2058 cmd.args.push(directory.as_os_str().into());
2059 }
2060 if self.warnings_into_errors {
2061 let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into();
2062 cmd.push_cc_arg(warnings_to_errors_flag);
2063 }
2064
2065 // If warnings and/or extra_warnings haven't been explicitly set,
2066 // then we set them only if the environment doesn't already have
2067 // CFLAGS/CXXFLAGS, since those variables presumably already contain
2068 // the desired set of warnings flags.
2069 let envflags = self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" })?;
2070 match self.warnings {
2071 Some(true) => {
2072 let wflags = cmd.family.warnings_flags().into();
2073 cmd.push_cc_arg(wflags);
2074 }
2075 Some(false) => {
2076 let wflags = cmd.family.warnings_suppression_flags().into();
2077 cmd.push_cc_arg(wflags);
2078 }
2079 None => {
2080 if envflags.is_none() {
2081 let wflags = cmd.family.warnings_flags().into();
2082 cmd.push_cc_arg(wflags);
2083 }
2084 }
2085 }
2086 if self.extra_warnings.unwrap_or(envflags.is_none()) {
2087 if let Some(wflags) = cmd.family.extra_warnings_flags() {
2088 cmd.push_cc_arg(wflags.into());
2089 }
2090 }
2091
2092 // Add cc flags inherited from matching rustc flags.
2093 if self.inherit_rustflags {
2094 self.add_inherited_rustflags(&mut cmd, &target)?;
2095 }
2096
2097 // Add path remap flags inherited from cargo's `-Ztrim-paths`.
2098 if self.inherit_trim_paths {
2099 self.add_trim_paths_flags(&mut cmd, &target)?;
2100 }
2101
2102 // Set flags configured in the builder (do this second-to-last, to allow these to override
2103 // everything above).
2104 for flag in self.flags.iter() {
2105 cmd.args.push((**flag).into());
2106 }
2107 for flag in self.flags_supported.iter() {
2108 if self
2109 .is_flag_supported_inner(flag, &cmd, &target)
2110 .unwrap_or(false)
2111 {
2112 cmd.push_cc_arg((**flag).into());
2113 }
2114 }
2115 for (key, value) in self.definitions.iter() {
2116 if let Some(ref value) = *value {
2117 cmd.args.push(format!("-D{key}={value}").into());
2118 } else {
2119 cmd.args.push(format!("-D{key}").into());
2120 }
2121 }
2122
2123 // Set flags from the environment (do this last, to allow these to override everything else).
2124 if let Some(flags) = &envflags {
2125 for arg in flags {
2126 cmd.push_cc_arg(arg.into());
2127 }
2128 }
2129
2130 // Set custom env vars that the user specified with `Build::env`.
2131 //
2132 // Do this last, to allow overwriting the other values above.
2133 for (key, val) in &self.env {
2134 cmd.env.push((key.into(), val.into()));
2135 }
2136
2137 Ok(cmd)
2138 }
2139
2140 fn add_default_flags(
2141 &self,
2142 cmd: &mut Tool,
2143 target: &TargetInfo<'_>,
2144 opt_level: &str,
2145 ) -> Result<(), Error> {
2146 let raw_target = self.get_raw_target()?;
2147 // Non-target flags
2148 // If the flag is not conditioned on target variable, it belongs here :)
2149 match cmd.family {
2150 ToolFamily::Msvc { .. } => {
2151 cmd.push_cc_arg("-nologo".into());
2152
2153 let crt_flag = match self.static_crt {
2154 Some(true) => "-MT",
2155 Some(false) => "-MD",
2156 None => {
2157 let features = cargo_env_var_os("CARGO_CFG_TARGET_FEATURE");
2158 let features = features.as_deref().unwrap_or_default();
2159 if features.to_string_lossy().contains("crt-static") {
2160 "-MT"
2161 } else {
2162 "-MD"
2163 }
2164 }
2165 };
2166 cmd.push_cc_arg(crt_flag.into());
2167
2168 match opt_level {
2169 // Msvc uses /O1 to enable all optimizations that minimize code size.
2170 "z" | "s" | "1" => cmd.push_opt_unless_duplicate("-O1".into()),
2171 // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2.
2172 "2" | "3" => cmd.push_opt_unless_duplicate("-O2".into()),
2173 _ => {}
2174 }
2175 }
2176 ToolFamily::Gnu | ToolFamily::Clang { .. } => {
2177 // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does
2178 // not support '-Oz'
2179 if opt_level == "z" && !cmd.is_like_clang() {
2180 cmd.push_opt_unless_duplicate("-Os".into());
2181 } else {
2182 cmd.push_opt_unless_duplicate(format!("-O{opt_level}").into());
2183 }
2184
2185 if cmd.is_like_clang() && target.os == "android" {
2186 // For compatibility with code that doesn't use pre-defined `__ANDROID__` macro.
2187 // If compiler used via ndk-build or cmake (officially supported build methods)
2188 // this macros is defined.
2189 // See https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/cmake/android.toolchain.cmake#456
2190 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/core/build-binary.mk#141
2191 cmd.push_opt_unless_duplicate("-DANDROID".into());
2192 }
2193
2194 if target.os != "ios"
2195 && target.os != "watchos"
2196 && target.os != "tvos"
2197 && target.os != "visionos"
2198 {
2199 cmd.push_cc_arg("-ffunction-sections".into());
2200 cmd.push_cc_arg("-fdata-sections".into());
2201 }
2202 // Disable generation of PIC on bare-metal for now: rust-lld doesn't support this yet
2203 //
2204 // `rustc` also defaults to disable PIC on WASM:
2205 // <https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_target/src/spec/base/wasm.rs#L101-L108>
2206 if self.pic.unwrap_or(
2207 target.os != "windows"
2208 && target.os != "none"
2209 && target.os != "uefi"
2210 && target.os != "vita"
2211 && target.arch != "wasm32"
2212 && target.arch != "wasm64",
2213 ) {
2214 cmd.push_cc_arg("-fPIC".into());
2215 // PLT only applies if code is compiled with PIC support,
2216 // and only for ELF targets.
2217 if (target.os == "linux" || target.os == "android")
2218 && !self.use_plt.unwrap_or(true)
2219 {
2220 cmd.push_cc_arg("-fno-plt".into());
2221 }
2222 }
2223
2224 if target.os == "wasi" {
2225 // Link clang sysroot
2226 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
2227 cmd.push_cc_arg(
2228 format!("--sysroot={}", Path::new(&wasi_sysroot).display()).into(),
2229 );
2230 }
2231
2232 // FIXME(madsmtm): Read from `target_features` instead?
2233 if raw_target.contains("threads") {
2234 cmd.push_cc_arg("-pthread".into());
2235 }
2236 }
2237
2238 if target.os == "nto" || target.os == "qnx" {
2239 // Select the target with `-V`, see qcc documentation:
2240 // QNX SDP 7.1: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/q/qcc.html
2241 // QNX SDP 8.0: https://www.qnx.com/developers/docs/8.0/com.qnx.doc.neutrino.utilities/topic/q/qcc.html
2242 // This assumes qcc/q++ as compiler, which is currently the only supported compiler for QNX.
2243 // See for details: https://github.com/rust-lang/cc-rs/pull/1319
2244 let arg = match target.full_arch {
2245 "x86" | "i586" => "-Vgcc_ntox86_cxx",
2246 "aarch64" => "-Vgcc_ntoaarch64le_cxx",
2247 "x86_64" => "-Vgcc_ntox86_64_cxx",
2248 _ => {
2249 return Err(Error::new(
2250 ErrorKind::InvalidTarget,
2251 format!("Unknown architecture for Neutrino QNX: {}", target.arch),
2252 ))
2253 }
2254 };
2255 cmd.push_cc_arg(arg.into());
2256 }
2257 }
2258 }
2259
2260 if self.get_debug() {
2261 if self.cuda {
2262 // NVCC debug flag
2263 cmd.args.push("-G".into());
2264 }
2265 let family = cmd.family;
2266 family.add_debug_flags(
2267 cmd,
2268 self.get_debug_str().as_deref().unwrap_or_default(),
2269 self.get_dwarf_version(),
2270 );
2271 }
2272
2273 if self.get_force_frame_pointer() {
2274 let family = cmd.family;
2275 if let ToolFamily::Gnu | ToolFamily::Clang { .. } = family {
2276 cmd.push_cc_arg("-fno-omit-frame-pointer".into());
2277 let flag = OsString::from("-mno-omit-leaf-frame-pointer");
2278 if self
2279 .is_flag_supported_inner(&flag, cmd, target)
2280 .unwrap_or(false)
2281 {
2282 cmd.push_cc_arg(flag);
2283 }
2284 }
2285 }
2286
2287 if !cmd.is_like_msvc() {
2288 if target.arch == "x86" {
2289 cmd.args.push("-m32".into());
2290 } else if target.abi == "x32" {
2291 cmd.args.push("-mx32".into());
2292 } else if target.os == "aix" {
2293 if cmd.family == ToolFamily::Gnu {
2294 cmd.args.push("-maix64".into());
2295 } else {
2296 cmd.args.push("-m64".into());
2297 }
2298 } else if target.arch == "x86_64" || target.arch == "powerpc64" {
2299 cmd.args.push("-m64".into());
2300 }
2301 }
2302
2303 // Target flags
2304 match cmd.family {
2305 ToolFamily::Clang { .. } => {
2306 if !(cmd.has_internal_target_arg
2307 || (target.os == "android"
2308 && android_clang_compiler_uses_target_arg_internally(&cmd.path)))
2309 {
2310 if target.os == "freebsd" {
2311 // FreeBSD only supports C++11 and above when compiling against libc++
2312 // (available from FreeBSD 10 onwards). Under FreeBSD, clang uses libc++ by
2313 // default on FreeBSD 10 and newer unless `--target` is manually passed to
2314 // the compiler, in which case its default behavior differs:
2315 // * If --target=xxx-unknown-freebsdX(.Y) is specified and X is greater than
2316 // or equal to 10, clang++ uses libc++
2317 // * If --target=xxx-unknown-freebsd is specified (without a version),
2318 // clang++ cannot assume libc++ is available and reverts to a default of
2319 // libstdc++ (this behavior was changed in llvm 14).
2320 //
2321 // This breaks C++11 (or greater) builds if targeting FreeBSD with the
2322 // generic xxx-unknown-freebsd target on clang 13 or below *without*
2323 // explicitly specifying that libc++ should be used.
2324 // When cross-compiling, we can't infer from the rust/cargo target name
2325 // which major version of FreeBSD we are targeting, so we need to make sure
2326 // that libc++ is used (unless the user has explicitly specified otherwise).
2327 // There's no compelling reason to use a different approach when compiling
2328 // natively.
2329 if self.cpp && self.cpp_set_stdlib.is_none() {
2330 cmd.push_cc_arg("-stdlib=libc++".into());
2331 }
2332 } else if target.arch == "wasm32" && target.os == "linux" {
2333 for x in &[
2334 "atomics",
2335 "bulk-memory",
2336 "mutable-globals",
2337 "sign-ext",
2338 "exception-handling",
2339 ] {
2340 cmd.push_cc_arg(format!("-m{x}").into());
2341 }
2342 for x in &["wasm-exceptions", "declspec"] {
2343 cmd.push_cc_arg(format!("-f{x}").into());
2344 }
2345 let musl_sysroot = self.wasm_musl_sysroot().unwrap();
2346 cmd.push_cc_arg(
2347 format!("--sysroot={}", Path::new(&musl_sysroot).display()).into(),
2348 );
2349 cmd.push_cc_arg("-pthread".into());
2350 } else if target.abi == "pauthtest" {
2351 let pauthtest_sysroot = self.pauthtest_sysroot()?;
2352 let pauthtest_resource_dir = self.pauthtest_resource_dir()?;
2353 cmd.push_cc_arg(
2354 format!("--sysroot={}", Path::new(&pauthtest_sysroot).display()).into(),
2355 );
2356 cmd.push_cc_arg(
2357 format!(
2358 "-resource-dir={}",
2359 Path::new(&pauthtest_resource_dir).display()
2360 )
2361 .into(),
2362 );
2363 cmd.push_cc_arg("-march=armv8.3-a+pauth".into());
2364 if self.cpp && self.cpp_set_stdlib.is_none() {
2365 cmd.push_cc_arg("-stdlib=libc++".into());
2366 cmd.push_cc_arg(
2367 format!(
2368 "-I{}/include/c++/v1",
2369 Path::new(&pauthtest_sysroot).display()
2370 )
2371 .into(),
2372 );
2373
2374 cmd.push_cc_arg(
2375 format!("-L{}/lib", Path::new(&pauthtest_sysroot).display()).into(),
2376 );
2377 }
2378 }
2379 // Pass `--target` with the LLVM target to configure Clang for cross-compiling.
2380 //
2381 // This is **required** for cross-compilation, as it's the only flag that
2382 // consistently forces Clang to change the "toolchain" that is responsible for
2383 // parsing target-specific flags:
2384 // https://github.com/rust-lang/cc-rs/issues/1388
2385 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/clang/lib/Driver/Driver.cpp#L1359-L1360
2386 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/clang/lib/Driver/Driver.cpp#L6347-L6532
2387 //
2388 // This can be confusing, because on e.g. host macOS, you can usually get by
2389 // with `-arch` and `-mtargetos=`. But that only works because the _default_
2390 // toolchain is `Darwin`, which enables parsing of darwin-specific options.
2391 //
2392 // NOTE: In the past, we passed the deployment version in here on all Apple
2393 // targets, but versioned targets were found to have poor compatibility with
2394 // older versions of Clang, especially when it comes to configuration files:
2395 // https://github.com/rust-lang/cc-rs/issues/1278
2396 //
2397 // So instead, we pass the deployment target with `-m*-version-min=`, and only
2398 // pass it here on visionOS and Mac Catalyst where that option does not exist:
2399 // https://github.com/rust-lang/cc-rs/issues/1383
2400 let version = if target.os == "visionos" || target.env == "macabi" {
2401 Some(self.apple_deployment_target(target))
2402 } else {
2403 None
2404 };
2405
2406 let clang_target =
2407 target.llvm_target(&self.get_raw_target()?, version.as_deref());
2408 cmd.push_cc_arg(format!("--target={clang_target}").into());
2409 }
2410 }
2411 ToolFamily::Msvc { clang_cl } => {
2412 // This is an undocumented flag from MSVC but helps with making
2413 // builds more reproducible by avoiding putting timestamps into
2414 // files.
2415 cmd.push_cc_arg("-Brepro".into());
2416
2417 if clang_cl {
2418 cmd.push_cc_arg(
2419 format!(
2420 "--target={}",
2421 target.llvm_target(&self.get_raw_target()?, None)
2422 )
2423 .into(),
2424 );
2425
2426 if target.arch == "x86" {
2427 // See
2428 // <https://learn.microsoft.com/en-us/cpp/build/reference/arch-x86?view=msvc-170>.
2429 //
2430 // NOTE: Rust officially supported Windows targets all require SSE2 as part
2431 // of baseline target features.
2432 //
2433 // NOTE: The same applies for STL. See: -
2434 // <https://github.com/microsoft/STL/issues/3922>, and -
2435 // <https://github.com/microsoft/STL/pull/4741>.
2436 cmd.push_cc_arg("-arch:SSE2".into());
2437 }
2438 } else if target.full_arch == "i586" {
2439 cmd.push_cc_arg("-arch:IA32".into());
2440 } else if target.full_arch == "arm64ec" {
2441 cmd.push_cc_arg("-arm64EC".into());
2442 }
2443 // There is a check in corecrt.h that will generate a
2444 // compilation error if
2445 // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is
2446 // not defined to 1. The check was added in Windows
2447 // 8 days because only store apps were allowed on ARM.
2448 // This changed with the release of Windows 10 IoT Core.
2449 // The check will be going away in future versions of
2450 // the SDK, but for all released versions of the
2451 // Windows SDK it is required.
2452 if target.arch == "arm" {
2453 cmd.args
2454 .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
2455 }
2456 }
2457 ToolFamily::Gnu => {
2458 if target.vendor == "kmc" {
2459 cmd.args.push("-finput-charset=utf-8".into());
2460 }
2461
2462 if self.static_flag.is_none() {
2463 let features = cargo_env_var_os("CARGO_CFG_TARGET_FEATURE");
2464 let features = features.as_deref().unwrap_or_default();
2465 if features.to_string_lossy().contains("crt-static") {
2466 cmd.args.push("-static".into());
2467 }
2468 }
2469
2470 // armv7 targets get to use armv7 instructions
2471 if (target.full_arch.starts_with("armv7")
2472 || target.full_arch.starts_with("thumbv7"))
2473 && (target.os == "linux" || target.vendor == "kmc")
2474 {
2475 cmd.args.push("-march=armv7-a".into());
2476
2477 if target.abi == "eabihf" {
2478 // lowest common denominator FPU
2479 cmd.args.push("-mfpu=vfpv3-d16".into());
2480 cmd.args.push("-mfloat-abi=hard".into());
2481 }
2482 }
2483
2484 // (x86 Android doesn't say "eabi")
2485 if target.os == "android" && target.full_arch.contains("v7") {
2486 cmd.args.push("-march=armv7-a".into());
2487 cmd.args.push("-mthumb".into());
2488 if !target.full_arch.contains("neon") {
2489 // On android we can guarantee some extra float instructions
2490 // (specified in the android spec online)
2491 // NEON guarantees even more; see below.
2492 cmd.args.push("-mfpu=vfpv3-d16".into());
2493 }
2494 cmd.args.push("-mfloat-abi=softfp".into());
2495 }
2496
2497 if target.full_arch.contains("neon") {
2498 cmd.args.push("-mfpu=neon".into());
2499 }
2500
2501 if target.full_arch == "armv4t" && target.os == "linux" {
2502 cmd.args.push("-march=armv4t".into());
2503 cmd.args.push("-marm".into());
2504 cmd.args.push("-mfloat-abi=soft".into());
2505 }
2506
2507 if target.full_arch == "armv5te" && target.os == "linux" {
2508 cmd.args.push("-march=armv5te".into());
2509 cmd.args.push("-marm".into());
2510 cmd.args.push("-mfloat-abi=soft".into());
2511 }
2512
2513 // For us arm == armv6 by default
2514 if target.full_arch == "arm" && target.os == "linux" {
2515 cmd.args.push("-march=armv6".into());
2516 cmd.args.push("-marm".into());
2517 if target.abi == "eabihf" {
2518 cmd.args.push("-mfpu=vfp".into());
2519 } else {
2520 cmd.args.push("-mfloat-abi=soft".into());
2521 }
2522 }
2523
2524 // Turn codegen down on i586 to avoid some instructions.
2525 if target.full_arch == "i586" && target.os == "linux" {
2526 cmd.args.push("-march=pentium".into());
2527 }
2528
2529 // Set codegen level for i686 correctly
2530 if target.full_arch == "i686" && target.os == "linux" {
2531 cmd.args.push("-march=i686".into());
2532 }
2533
2534 // Looks like `musl-gcc` makes it hard for `-m32` to make its way
2535 // all the way to the linker, so we need to actually instruct the
2536 // linker that we're generating 32-bit executables as well. This'll
2537 // typically only be used for build scripts which transitively use
2538 // these flags that try to compile executables.
2539 if target.arch == "x86" && target.env == "musl" {
2540 cmd.args.push("-Wl,-melf_i386".into());
2541 }
2542
2543 //
2544 // Arm Target Details
2545 //
2546
2547 // Set Float ABI for all Arm bare-metal targets using EABIHF
2548 if target.arch == "arm" && target.os == "none" && target.abi == "eabihf" {
2549 cmd.args.push("-mfloat-abi=hard".into())
2550 }
2551 // Set -mthumb for all Thumb targets
2552 if target.full_arch.starts_with("thumb") {
2553 cmd.args.push("-mthumb".into());
2554 }
2555 // Armv6-M targets (no FPU available)
2556 if target.full_arch.starts_with("thumbv6m") {
2557 // ARMv6S-M is an old name for "ARMv6-M with SVC support"
2558 // before SVC support became mandatory. Some versions of GAS care
2559 // about the difference.
2560 cmd.args.push("-march=armv6s-m".into());
2561 }
2562 // Armv7-M targets (no FPU available)
2563 if target.full_arch.starts_with("thumbv7m") {
2564 cmd.args.push("-march=armv7-m".into());
2565 }
2566 // Armv7E-M targets
2567 if target.full_arch.starts_with("thumbv7em") {
2568 cmd.args.push("-march=armv7e-m".into());
2569 if target.abi == "eabihf" {
2570 cmd.args.push("-mfpu=fpv4-sp-d16".into())
2571 }
2572 }
2573 // Armv8-M Baseline (no FPU available)
2574 if target.full_arch.starts_with("thumbv8m.base") {
2575 cmd.args.push("-march=armv8-m.base".into());
2576 }
2577 // Armv8-M Mainline targets
2578 if target.full_arch.starts_with("thumbv8m.main") {
2579 cmd.args.push("-march=armv8-m.main".into());
2580 if target.abi == "eabihf" {
2581 cmd.args.push("-mfpu=fpv5-sp-d16".into())
2582 }
2583 }
2584 // ARMv6 targets
2585 if target.full_arch.starts_with("armv6")
2586 || (target.full_arch.starts_with("thumbv6")
2587 && !target.full_arch.starts_with("thumbv6m"))
2588 {
2589 cmd.args.push("-march=armv6".into());
2590 if target.abi == "eabihf" {
2591 // lowest common denominator FPU
2592 cmd.args.push("-mfpu=vfpv2".into());
2593 }
2594 }
2595 // ARMv7-R targets
2596 if target.full_arch.starts_with("armebv7r")
2597 || target.full_arch.starts_with("armv7r")
2598 || target.full_arch.starts_with("thumbv7r")
2599 {
2600 if target.full_arch.starts_with("armeb") {
2601 cmd.args.push("-mbig-endian".into());
2602 }
2603 cmd.args.push("-march=armv7-r".into());
2604 if target.abi == "eabihf" {
2605 // lowest common denominator FPU
2606 // (see Cortex-R4 technical reference manual)
2607 cmd.args.push("-mfpu=vfpv3-d16".into())
2608 }
2609 }
2610 // Armv7-A targets
2611 if target.full_arch.starts_with("armv7a")
2612 || target.full_arch.starts_with("thumbv7a")
2613 {
2614 cmd.args.push("-march=armv7-a".into());
2615 if target.abi == "eabihf" {
2616 // lowest common denominator FPU
2617 cmd.args.push("-mfpu=vfpv3-d16".into());
2618 }
2619 }
2620 // Armv8-R targets
2621 if target.full_arch.starts_with("armv8r")
2622 || target.full_arch.starts_with("thumbv8r")
2623 {
2624 cmd.args.push("-march=armv8-r".into());
2625 if target.abi == "eabihf" {
2626 cmd.args.push("-mfpu=fp-armv8".into())
2627 }
2628 }
2629
2630 if target.arch == "riscv32" || target.arch == "riscv64" {
2631 // get the 32i/32imac/32imc/64gc/64imac/... part
2632 let arch = &target.full_arch[5..];
2633 if arch.starts_with("64") {
2634 if matches!(target.os, "linux" | "freebsd" | "netbsd" | "managarm") {
2635 cmd.args.push(("-march=rv64gc").into());
2636 cmd.args.push("-mabi=lp64d".into());
2637 } else {
2638 cmd.args.push(("-march=rv".to_owned() + arch).into());
2639 cmd.args.push("-mabi=lp64".into());
2640 }
2641 } else if arch.starts_with("32") {
2642 if target.os == "linux" {
2643 cmd.args.push(("-march=rv32gc").into());
2644 cmd.args.push("-mabi=ilp32d".into());
2645 } else {
2646 cmd.args.push(("-march=rv".to_owned() + arch).into());
2647 cmd.args.push("-mabi=ilp32".into());
2648 }
2649 } else {
2650 cmd.args.push("-mcmodel=medany".into());
2651 }
2652 }
2653 }
2654 }
2655
2656 if raw_target == "wasm32v1-none" {
2657 // `wasm32v1-none` target only exists in `rustc`, so we need to change the compilation flags:
2658 // https://doc.rust-lang.org/rustc/platform-support/wasm32v1-none.html
2659 cmd.push_cc_arg("-mcpu=mvp".into());
2660 cmd.push_cc_arg("-mmutable-globals".into());
2661 }
2662
2663 if target.os == "solaris" || target.os == "illumos" {
2664 // On Solaris and illumos, multi-threaded C programs must be built with `_REENTRANT`
2665 // defined. This configures headers to define APIs appropriately for multi-threaded
2666 // use. This is documented in threads(7), see also https://illumos.org/man/7/threads.
2667 //
2668 // If C code is compiled without multi-threading support but does use multiple threads,
2669 // incorrect behavior may result. One extreme example is that on some systems the
2670 // global errno may be at the same address as the process' first thread's errno; errno
2671 // clobbering may occur to disastrous effect. Conversely, if _REENTRANT is defined
2672 // while it is not actually needed, system headers may define some APIs suboptimally
2673 // but will not result in incorrect behavior. Other code *should* be reasonable under
2674 // such conditions.
2675 //
2676 // We're typically building C code to eventually link into a Rust program. Many Rust
2677 // programs are multi-threaded in some form. So, set the flag by default.
2678 cmd.args.push("-D_REENTRANT".into());
2679 }
2680
2681 if target.vendor == "apple" {
2682 self.apple_flags(cmd)?;
2683 }
2684
2685 if self.static_flag.unwrap_or(false) {
2686 cmd.args.push("-static".into());
2687 }
2688 if self.shared_flag.unwrap_or(false) {
2689 cmd.args.push("-shared".into());
2690 }
2691
2692 if self.cpp {
2693 match (self.cpp_set_stdlib.as_ref(), cmd.family) {
2694 (None, _) => {}
2695 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang { .. }) => {
2696 cmd.push_cc_arg(format!("-stdlib=lib{stdlib}").into());
2697 }
2698 _ => {
2699 self.cargo_output.print_warning(&format_args!("cpp_set_stdlib is specified, but the {:?} compiler does not support this option, ignored", cmd.family));
2700 }
2701 }
2702 }
2703
2704 Ok(())
2705 }
2706
2707 fn add_inherited_rustflags(
2708 &self,
2709 cmd: &mut Tool,
2710 target: &TargetInfo<'_>,
2711 ) -> Result<(), Error> {
2712 let Some(env_os) = cargo_env_var_os("CARGO_ENCODED_RUSTFLAGS") else {
2713 // No encoded RUSTFLAGS -> nothing to do
2714 return Ok(());
2715 };
2716
2717 let env = env_os.to_string_lossy();
2718 let codegen_flags = RustcCodegenFlags::parse(&env)?;
2719 codegen_flags.cc_flags(self, cmd, target);
2720 Ok(())
2721 }
2722
2723 /// Translate cargo's `-Ztrim-paths` remap rules into compiler flags.
2724 ///
2725 /// [`trim-paths`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#profile-trim-paths-option
2726 fn add_trim_paths_flags(&self, cmd: &mut Tool, target: &TargetInfo<'_>) -> Result<(), Error> {
2727 // Native MSVC has no documented equivalent of the `-f*-prefix-map` flag family.
2728 // clang-cl parses Clang driver options when wrapped in `/clang:`.
2729 if cmd.is_like_msvc() && !cmd.is_like_clang_cl() {
2730 return Ok(());
2731 }
2732 let Some(scope) = cargo_env_var_os("CARGO_TRIM_PATHS_SCOPE") else {
2733 return Ok(());
2734 };
2735 let Some(remap) = cargo_env_var_os("CARGO_TRIM_PATHS_REMAP") else {
2736 return Ok(());
2737 };
2738
2739 // * `macro` scope -> `-fmacro-prefix-map`
2740 // * `object` scope -> `-fmacro-prefix-map` + `-fdebug-prefix-map`
2741 // * `all` scope -> both
2742 // * `diagnostics` and `none` scopes have no C equivalent
2743 let mut macro_scope = false;
2744 let mut object_scope = false;
2745 for scope in scope.to_string_lossy().split(',') {
2746 match scope {
2747 "all" => {
2748 macro_scope = true;
2749 object_scope = true;
2750 break;
2751 }
2752 // `__FILE__` and friends
2753 "macro" => macro_scope = true,
2754 // Everything embedded in object files.
2755 // rustc defines this scope as macro + debuginfo.
2756 // Both `__FILE__` strings and debug info end up in the object,
2757 // so the C analogue must remap both as well.
2758 "object" => {
2759 macro_scope = true;
2760 object_scope = true;
2761 break;
2762 }
2763 _ => {}
2764 }
2765 }
2766
2767 let macro_scope =
2768 macro_scope && self.probe_prefix_map_flag(PrefixMapFlag::Macro, cmd, target);
2769 let object_scope =
2770 object_scope && self.probe_prefix_map_flag(PrefixMapFlag::Debug, cmd, target);
2771
2772 if !macro_scope && !object_scope {
2773 return Ok(());
2774 }
2775
2776 // clang-cl parses Clang driver options when wrapped in `/clang:`.
2777 // <https://clang.llvm.org/docs/UsersManual.html#the-clang-option>
2778 let clang_driver = if cmd.is_like_clang_cl() {
2779 "/clang:"
2780 } else {
2781 ""
2782 };
2783
2784 for pair in env::split_paths(&remap) {
2785 let pair = pair.as_os_str();
2786 if pair.is_empty() {
2787 continue;
2788 }
2789 if macro_scope {
2790 let mut flag = OsString::from(clang_driver);
2791 flag.push("-fmacro-prefix-map=");
2792 flag.push(pair);
2793 cmd.push_cc_arg(flag);
2794 }
2795 if object_scope {
2796 let mut flag = OsString::from(clang_driver);
2797 flag.push("-fdebug-prefix-map=");
2798 flag.push(pair);
2799 cmd.push_cc_arg(flag);
2800 }
2801 }
2802 Ok(())
2803 }
2804
2805 /// Check if `-f*-prefix-map` flag is supported.
2806 ///
2807 /// * `-fdebug-prefix-map`: supported since GCC 4.3 (2008-03), Clang 3.8 (2016-03):
2808 /// * <https://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Debugging-Options.html>
2809 /// * <https://github.com/llvm/llvm-project/commit/436256a71316a1e6ad68ebee8439c88d75>
2810 /// * `-fmacro-prefix-map`: supported since GCC 8.1 (2018-05), Clang 10.0 (2020-03)
2811 /// * <https://gcc.gnu.org/onlinedocs/gcc-8.1.0/gcc/Option-Summary.html>
2812 /// * <https://releases.llvm.org/10.0.0/tools/clang/docs/ReleaseNotes.html>
2813 fn probe_prefix_map_flag(
2814 &self,
2815 flag: PrefixMapFlag,
2816 cmd: &Tool,
2817 target: &TargetInfo<'_>,
2818 ) -> bool {
2819 let (flag, unsupported_warning) = match flag {
2820 PrefixMapFlag::Macro => (
2821 "-fmacro-prefix-map",
2822 "paths embedded by macros will not be remapped",
2823 ),
2824 PrefixMapFlag::Debug => (
2825 "-fdebug-prefix-map",
2826 "paths embedded in debug info will not be remapped",
2827 ),
2828 };
2829 // clang-cl parses Clang driver options when wrapped in `/clang:`.
2830 // <https://clang.llvm.org/docs/UsersManual.html#the-clang-option>
2831 let flag = if cmd.is_like_clang_cl() {
2832 format!("/clang:{flag}")
2833 } else {
2834 flag.to_owned()
2835 };
2836 let probe = format!("{flag}=/probe=/probe");
2837 let supported = self
2838 .is_flag_supported_inner(OsStr::new(&probe), cmd, target)
2839 .unwrap_or(false);
2840
2841 if !supported {
2842 self.cargo_output.print_warning(&format_args!(
2843 "{flag} is not supported by {:?}, {unsupported_warning}",
2844 cmd.path()
2845 ));
2846 }
2847
2848 supported
2849 }
2850
2851 fn msvc_macro_assembler(&self) -> Result<Command, Error> {
2852 let target = self.get_target()?;
2853 let tool = match target.arch {
2854 "x86_64" => "ml64.exe",
2855 "arm" => "armasm.exe",
2856 "aarch64" | "arm64ec" => "armasm64.exe",
2857 _ => "ml.exe",
2858 };
2859 let mut cmd = self
2860 .find_msvc_tools_find(&target, tool)
2861 .unwrap_or_else(|| self.cmd(tool));
2862 cmd.arg("-nologo"); // undocumented, yet working with armasm[64]
2863 for directory in self.include_directories.iter() {
2864 cmd.arg("-I").arg(&**directory);
2865 }
2866 if is_arm(&target) {
2867 if self.get_debug() {
2868 cmd.arg("-g");
2869 }
2870
2871 if target.arch == "arm64ec" {
2872 cmd.args(["-machine", "ARM64EC"]);
2873 }
2874
2875 for (key, value) in self.definitions.iter() {
2876 cmd.arg("-PreDefine");
2877 if let Some(ref value) = *value {
2878 if let Ok(i) = value.parse::<i32>() {
2879 cmd.arg(format!("{key} SETA {i}"));
2880 } else if value.starts_with('"') && value.ends_with('"') {
2881 cmd.arg(format!("{key} SETS {value}"));
2882 } else {
2883 cmd.arg(format!("{key} SETS \"{value}\""));
2884 }
2885 } else {
2886 cmd.arg(format!("{} SETL {}", key, "{TRUE}"));
2887 }
2888 }
2889 } else {
2890 if self.get_debug() {
2891 cmd.arg("-Zi");
2892 }
2893
2894 for (key, value) in self.definitions.iter() {
2895 if let Some(ref value) = *value {
2896 cmd.arg(format!("-D{key}={value}"));
2897 } else {
2898 cmd.arg(format!("-D{key}"));
2899 }
2900 }
2901 }
2902
2903 if target.arch == "x86" {
2904 cmd.arg("-safeseh");
2905 }
2906
2907 Ok(cmd)
2908 }
2909
2910 fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
2911 // Delete the destination if it exists as we want to
2912 // create on the first iteration instead of appending.
2913 let _ = fs::remove_file(dst);
2914
2915 // Add objects to the archive in limited-length batches. This helps keep
2916 // the length of the command line within a reasonable length to avoid
2917 // blowing system limits on limiting platforms like Windows.
2918 //
2919 // Optimistically try the `D` (deterministic) ar modifier, which zeros
2920 // out timestamps, UIDs, and GIDs. If the archiver doesn't support it,
2921 // we remember and stop trying for subsequent batches.
2922 // (`None` -> haven't probed yet)
2923 let mut deterministic_ar: Option<bool> = None;
2924
2925 let mut objs = objs
2926 .iter()
2927 .map(|o| o.dst.as_path())
2928 .chain(self.objects.iter().map(std::ops::Deref::deref))
2929 .peekable();
2930 let mut batch = Vec::new();
2931 while objs.peek().is_some() {
2932 let mut remaining_len = 4000;
2933 while let Some(path) =
2934 objs.next_if(|peek| batch.is_empty() || peek.as_os_str().len() <= remaining_len)
2935 {
2936 batch.push(path);
2937 remaining_len = remaining_len.saturating_sub(path.as_os_str().len());
2938 }
2939 self.assemble_progressive(dst, &batch, &mut deterministic_ar)?;
2940 batch.clear();
2941 }
2942
2943 if self.cuda && self.cuda_file_count() > 0 {
2944 // Link the device-side code and add it to the target library,
2945 // so that non-CUDA linker can link the final binary.
2946
2947 let out_dir = self.get_out_dir()?;
2948 let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o");
2949 let mut nvcc = self.get_compiler().to_command();
2950 nvcc.arg("--device-link").arg("-o").arg(&dlink).arg(dst);
2951 run(&mut nvcc, &self.cargo_output)?;
2952 self.assemble_progressive(dst, &[dlink.as_path()], &mut deterministic_ar)?;
2953 }
2954
2955 let target = self.get_target()?;
2956 if target.env == "msvc" {
2957 // The Rust compiler will look for libfoo.a and foo.lib, but the
2958 // MSVC linker will also be passed foo.lib, so be sure that both
2959 // exist for now.
2960
2961 let lib_dst = dst.with_file_name(format!("{lib_name}.lib"));
2962 let _ = fs::remove_file(&lib_dst);
2963 match fs::hard_link(dst, &lib_dst).or_else(|_| {
2964 // if hard-link fails, just copy (ignoring the number of bytes written)
2965 fs::copy(dst, &lib_dst).map(|_| ())
2966 }) {
2967 Ok(_) => (),
2968 Err(_) => {
2969 return Err(Error::new(
2970 ErrorKind::IOError,
2971 "Could not copy or create a hard-link to the generated lib file.",
2972 ));
2973 }
2974 };
2975 } else {
2976 // Non-msvc targets (those using `ar`) need a separate step to add
2977 // the symbol table to archives since our construction command of
2978 // `cq` doesn't add it for us.
2979 let mut ar = self.try_get_archiver()?;
2980 // NOTE: We add `s` even if flags were passed using $ARFLAGS/ar_flag, because `s`
2981 // here represents a _mode_, not an arbitrary flag. Further discussion of this choice
2982 // can be seen in https://github.com/rust-lang/cc-rs/pull/763.
2983 match deterministic_ar {
2984 Some(false) => {
2985 // See comment in `assemble_progressive` for more on ZERO_AR_DATE.
2986 ar.env("ZERO_AR_DATE", "1");
2987 run(ar.arg("s").arg(dst), &self.cargo_output)?;
2988 }
2989 Some(true) => {
2990 run(ar.arg("sD").arg(dst), &self.cargo_output)?;
2991 }
2992 None => {
2993 if run_silent_on_error(ar.arg("sD").arg(dst), &self.cargo_output).is_err() {
2994 let mut ar = self.try_get_archiver()?;
2995 ar.env("ZERO_AR_DATE", "1");
2996 run(ar.arg("s").arg(dst), &self.cargo_output)?;
2997 }
2998 }
2999 }
3000 }
3001
3002 Ok(())
3003 }
3004
3005 fn assemble_progressive(
3006 &self,
3007 dst: &Path,
3008 objs: &[&Path],
3009 deterministic_ar: &mut Option<bool>,
3010 ) -> Result<(), Error> {
3011 let target = self.get_target()?;
3012
3013 let (mut cmd, program, any_flags) = self.try_get_archiver_and_flags()?;
3014 if target.env == "msvc" && !program.to_string_lossy().contains("llvm-ar") {
3015 // NOTE: -out: here is an I/O flag, and so must be included even if $ARFLAGS/ar_flag is
3016 // in use. -nologo on the other hand is just a regular flag, and one that we'll skip if
3017 // the caller has explicitly dictated the flags they want. See
3018 // https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
3019 let mut out = OsString::from("-out:");
3020 out.push(dst);
3021 cmd.arg(out);
3022 if !any_flags {
3023 cmd.arg("-nologo");
3024 }
3025 // If the library file already exists, add the library name
3026 // as an argument to let lib.exe know we are appending the objs.
3027 if dst.exists() {
3028 cmd.arg(dst);
3029 }
3030 cmd.args(objs);
3031 run(&mut cmd, &self.cargo_output)?;
3032 } else {
3033 // Set an environment variable to tell the OSX archiver to ensure
3034 // that all dates listed in the archive are zero, improving
3035 // determinism of builds. AFAIK there's not really official
3036 // documentation of this but there's a lot of references to it if
3037 // you search google.
3038 //
3039 // You can reproduce this locally on a mac with:
3040 //
3041 // $ touch foo.c
3042 // $ cc -c foo.c -o foo.o
3043 //
3044 // # Notice that these two checksums are different
3045 // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
3046 // $ md5sum libfoo*.a
3047 //
3048 // # Notice that these two checksums are the same
3049 // $ export ZERO_AR_DATE=1
3050 // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
3051 // $ md5sum libfoo*.a
3052 //
3053 // In any case if this doesn't end up getting read, it shouldn't
3054 // cause that many issues!
3055 cmd.env("ZERO_AR_DATE", "1");
3056
3057 // NOTE: We add cq here regardless of whether $ARFLAGS/ar_flag have been used because
3058 // it dictates the _mode_ ar runs in, which the setter of $ARFLAGS/ar_flag can't
3059 // dictate. See https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
3060 match *deterministic_ar {
3061 Some(false) => {
3062 run(cmd.arg("cq").arg(dst).args(objs), &self.cargo_output)?;
3063 }
3064 Some(true) => {
3065 run(cmd.arg("cqD").arg(dst).args(objs), &self.cargo_output)?;
3066 }
3067 None => {
3068 // Probe: try `D` and remember the result for later batches.
3069 if run_silent_on_error(cmd.arg("cqD").arg(dst).args(objs), &self.cargo_output)
3070 .is_ok()
3071 {
3072 *deterministic_ar = Some(true);
3073 } else {
3074 *deterministic_ar = Some(false);
3075 let (mut cmd, _, _) = self.try_get_archiver_and_flags()?;
3076 cmd.env("ZERO_AR_DATE", "1");
3077 run(cmd.arg("cq").arg(dst).args(objs), &self.cargo_output)?;
3078 }
3079 }
3080 }
3081 }
3082
3083 Ok(())
3084 }
3085
3086 fn apple_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
3087 let target = self.get_target()?;
3088
3089 // This is a Darwin/Apple-specific flag that works both on GCC and Clang, but it is only
3090 // necessary on GCC since we specify `-target` on Clang.
3091 // https://gcc.gnu.org/onlinedocs/gcc/Darwin-Options.html#:~:text=arch
3092 // https://clang.llvm.org/docs/CommandGuide/clang.html#cmdoption-arch
3093 if cmd.is_like_gnu() {
3094 let arch = map_darwin_target_from_rust_to_compiler_architecture(&target);
3095 cmd.args.push("-arch".into());
3096 cmd.args.push(arch.into());
3097 }
3098
3099 // Pass the deployment target via `-mmacosx-version-min=`, `-miphoneos-version-min=` and
3100 // similar. Also necessary on GCC, as it forces a compilation error if the compiler is not
3101 // configured for Darwin: https://gcc.gnu.org/onlinedocs/gcc/Darwin-Options.html
3102 //
3103 // On visionOS and Mac Catalyst, there is no -m*-version-min= flag:
3104 // https://github.com/llvm/llvm-project/issues/88271
3105 // And the workaround to use `-mtargetos=` cannot be used with the `--target` flag that we
3106 // otherwise specify. So we avoid emitting that, and put the version in `--target` instead.
3107 if cmd.is_like_gnu() || !(target.os == "visionos" || target.env == "macabi") {
3108 let min_version = self.apple_deployment_target(&target);
3109 cmd.args
3110 .push(target.apple_version_flag(&min_version).into());
3111 }
3112
3113 // AppleClang sometimes requires sysroot even on macOS
3114 if cmd.is_xctoolchain_clang() || target.os != "macos" {
3115 self.cargo_output.print_metadata(&format_args!(
3116 "Detecting {:?} SDK path for {}",
3117 target.os,
3118 target.apple_sdk_name(),
3119 ));
3120 let sdk_path = self.apple_sdk_root(&target)?;
3121
3122 cmd.args.push("-isysroot".into());
3123 cmd.args.push(OsStr::new(&sdk_path).to_owned());
3124 cmd.env
3125 .push(("SDKROOT".into(), OsStr::new(&sdk_path).to_owned()));
3126
3127 if target.env == "macabi" {
3128 // Mac Catalyst uses the macOS SDK, but to compile against and
3129 // link to iOS-specific frameworks, we should have the support
3130 // library stubs in the include and library search path.
3131 let ios_support = Path::new(&sdk_path).join("System/iOSSupport");
3132
3133 cmd.args.extend([
3134 // Header search path
3135 OsString::from("-isystem"),
3136 ios_support.join("usr/include").into(),
3137 // Framework header search path
3138 OsString::from("-iframework"),
3139 ios_support.join("System/Library/Frameworks").into(),
3140 // Library search path
3141 {
3142 let mut s = OsString::from("-L");
3143 s.push(ios_support.join("usr/lib"));
3144 s
3145 },
3146 // Framework linker search path
3147 {
3148 // Technically, we _could_ avoid emitting `-F`, as
3149 // `-iframework` implies it, but let's keep it in for
3150 // clarity.
3151 let mut s = OsString::from("-F");
3152 s.push(ios_support.join("System/Library/Frameworks"));
3153 s
3154 },
3155 ]);
3156 }
3157 }
3158
3159 Ok(())
3160 }
3161
3162 fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
3163 let mut cmd = Command::new(prog);
3164 for (a, b) in self.env.iter() {
3165 cmd.env(a, b);
3166 }
3167 cmd
3168 }
3169
3170 fn prefer_clang(&self) -> bool {
3171 if let Some(env) = cargo_env_var_os("CARGO_ENCODED_RUSTFLAGS") {
3172 env.to_string_lossy().contains("linker-plugin-lto")
3173 } else {
3174 false
3175 }
3176 }
3177
3178 fn get_base_compiler(&self) -> Result<Tool, Error> {
3179 let out_dir = self.get_out_dir().ok();
3180 let out_dir = out_dir.as_deref();
3181
3182 if let Some(c) = &self.compiler {
3183 return Ok(Tool::new(
3184 (**c).to_owned(),
3185 &self.env,
3186 &self.build_cache.cached_compiler_family,
3187 &self.cargo_output,
3188 out_dir,
3189 ));
3190 }
3191 let target = self.get_target()?;
3192 let raw_target = self.get_raw_target()?;
3193
3194 let msvc = if self.prefer_clang_cl_over_msvc {
3195 "clang-cl.exe"
3196 } else {
3197 "cl.exe"
3198 };
3199
3200 let (env, gnu, traditional, clang) = if self.cpp {
3201 ("CXX", "g++", "c++", "clang++")
3202 } else {
3203 ("CC", "gcc", "cc", "clang")
3204 };
3205
3206 let fallback = Cow::Borrowed(Path::new(traditional));
3207 let default = if cfg!(target_os = "solaris") || cfg!(target_os = "illumos") {
3208 // On historical Solaris systems, "cc" may have been Sun Studio, which
3209 // is not flag-compatible with "gcc". This history casts a long shadow,
3210 // and many modern illumos distributions today ship GCC as "gcc" without
3211 // also making it available as "cc".
3212 Cow::Borrowed(Path::new(gnu))
3213 } else if self.prefer_clang() || target.abi == "pauthtest" {
3214 self.which(Path::new(clang), None)
3215 .map(Cow::Owned)
3216 .unwrap_or(fallback)
3217 } else {
3218 fallback
3219 };
3220
3221 let cl_exe = self.find_msvc_tools_find_tool(&target, msvc);
3222
3223 let tool_opt: Option<Tool> = self
3224 .env_tool(env)
3225 .map(|(tool, wrapper, args)| {
3226 // Chop off leading/trailing whitespace to work around
3227 // semi-buggy build scripts which are shared in
3228 // makefiles/configure scripts (where spaces are far more
3229 // lenient)
3230 let mut t = Tool::with_args(
3231 tool,
3232 args.clone(),
3233 &self.env,
3234 &self.build_cache.cached_compiler_family,
3235 &self.cargo_output,
3236 out_dir,
3237 );
3238 if let Some(cc_wrapper) = wrapper {
3239 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
3240 }
3241 for arg in args {
3242 t.cc_wrapper_args.push(arg.into());
3243 }
3244 t
3245 })
3246 .or_else(|| {
3247 if target.os == "emscripten" {
3248 let tool = if self.cpp { "em++" } else { "emcc" };
3249 // Windows uses bat file so we have to be a bit more specific
3250 if cfg!(windows) {
3251 let mut t = Tool::with_family(
3252 PathBuf::from("cmd"),
3253 ToolFamily::Clang { zig_cc: false },
3254 );
3255 t.args.push("/c".into());
3256 t.args.push(format!("{tool}.bat").into());
3257 Some(t)
3258 } else {
3259 Some(Tool::new(
3260 PathBuf::from(tool),
3261 &self.env,
3262 &self.build_cache.cached_compiler_family,
3263 &self.cargo_output,
3264 out_dir,
3265 ))
3266 }
3267 } else {
3268 None
3269 }
3270 })
3271 .or_else(|| cl_exe.clone());
3272
3273 let tool = match tool_opt {
3274 Some(t) => t,
3275 None => {
3276 let compiler: PathBuf = if cfg!(windows) && target.os == "windows" {
3277 if target.env == "msvc" {
3278 msvc.into()
3279 } else {
3280 let cc = if target.abi == "llvm" { clang } else { gnu };
3281 format!("{cc}.exe").into()
3282 }
3283 } else if target.os == "ios"
3284 || target.os == "watchos"
3285 || target.os == "tvos"
3286 || target.os == "visionos"
3287 {
3288 clang.into()
3289 } else if target.os == "android" {
3290 autodetect_android_compiler(&raw_target, gnu, clang)
3291 } else if target.os == "cloudabi" {
3292 format!(
3293 "{}-{}-{}-{}",
3294 target.full_arch, target.vendor, target.os, traditional
3295 )
3296 .into()
3297 } else if target.os == "wasi" {
3298 self.autodetect_wasi_compiler(&raw_target, clang)
3299 } else if target.arch == "wasm32" || target.arch == "wasm64" {
3300 // Compiling WASM is not currently supported by GCC, so
3301 // let's default to Clang.
3302 clang.into()
3303 } else if target.os == "vxworks" {
3304 if self.cpp { "wr-c++" } else { "wr-cc" }.into()
3305 } else if target.arch == "arm" && target.vendor == "kmc" {
3306 format!("arm-kmc-eabi-{gnu}").into()
3307 } else if target.arch == "aarch64" && target.vendor == "kmc" {
3308 format!("aarch64-kmc-elf-{gnu}").into()
3309 } else if target.os == "nto" || target.os == "qnx" {
3310 // See for details: https://github.com/rust-lang/cc-rs/pull/1319
3311 if self.cpp { "q++" } else { "qcc" }.into()
3312 } else if self.get_is_cross_compile()? {
3313 let prefix = self.prefix_for_target(&raw_target);
3314 match prefix {
3315 Some(prefix) => {
3316 let cc = if target.abi == "llvm" { clang } else { gnu };
3317 format!("{prefix}-{cc}").into()
3318 }
3319 None => default.into(),
3320 }
3321 } else {
3322 default.into()
3323 };
3324
3325 let mut t = Tool::new(
3326 compiler,
3327 &self.env,
3328 &self.build_cache.cached_compiler_family,
3329 &self.cargo_output,
3330 out_dir,
3331 );
3332 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
3333 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
3334 }
3335 t
3336 }
3337 };
3338
3339 let mut tool = if self.cuda {
3340 assert!(
3341 tool.args.is_empty(),
3342 "CUDA compilation currently assumes empty pre-existing args"
3343 );
3344 let nvcc = match self.getenv_with_target_prefixes("NVCC") {
3345 Err(_) => PathBuf::from("nvcc"),
3346 Ok(nvcc) => PathBuf::from(&*nvcc),
3347 };
3348 let mut nvcc_tool = Tool::with_features(
3349 nvcc,
3350 vec![],
3351 self.cuda,
3352 &self.env,
3353 &self.build_cache.cached_compiler_family,
3354 &self.cargo_output,
3355 out_dir,
3356 );
3357 if self.ccbin {
3358 nvcc_tool
3359 .args
3360 .push(format!("-ccbin={}", tool.path.display()).into());
3361 }
3362 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
3363 nvcc_tool.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
3364 }
3365 nvcc_tool.family = tool.family;
3366 nvcc_tool
3367 } else {
3368 tool
3369 };
3370
3371 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
3372 // are just shell scripts that call main clang binary (from Android NDK) with
3373 // proper `--target` argument.
3374 //
3375 // For example, armv7a-linux-androideabi16-clang passes
3376 // `--target=armv7a-linux-androideabi16` to clang.
3377 //
3378 // As the shell script calls the main clang binary, the command line limit length
3379 // on Windows is restricted to around 8k characters instead of around 32k characters.
3380 // To remove this limit, we call the main clang binary directly and construct the
3381 // `--target=` ourselves.
3382 if cfg!(windows) && android_clang_compiler_uses_target_arg_internally(&tool.path) {
3383 if let Some(path) = tool.path.file_name() {
3384 let file_name = path.to_str().unwrap().to_owned();
3385 let (target, clang) = file_name.split_at(file_name.rfind('-').unwrap());
3386
3387 tool.has_internal_target_arg = true;
3388 tool.path.set_file_name(clang.trim_start_matches('-'));
3389 tool.path.set_extension("exe");
3390 tool.args.push(format!("--target={target}").into());
3391
3392 // Additionally, shell scripts for target i686-linux-android versions 16 to 24
3393 // pass the `mstackrealign` option so we do that here as well.
3394 if target.contains("i686-linux-android") {
3395 let (_, version) = target.split_at(target.rfind('d').unwrap() + 1);
3396 if let Ok(version) = version.parse::<u32>() {
3397 if version > 15 && version < 25 {
3398 tool.args.push("-mstackrealign".into());
3399 }
3400 }
3401 }
3402 };
3403 }
3404
3405 // Under cross-compilation scenarios, llvm-mingw's clang executable is just a
3406 // wrapper script that calls the actual clang binary with a suitable `--target`
3407 // argument, much like the Android NDK case outlined above. Passing a target
3408 // argument ourselves in this case will result in an error, as they expect
3409 // targets like `x86_64-w64-mingw32`, and we can't always set such a target
3410 // string because it is specific to this MinGW cross-compilation toolchain.
3411 //
3412 // For example, the following command will always fail due to using an unsuitable
3413 // `--target` argument we'd otherwise pass:
3414 // $ /opt/llvm-mingw-20250613-ucrt-ubuntu-22.04-x86_64/bin/x86_64-w64-mingw32-clang --target=x86_64-pc-windows-gnu dummy.c
3415 //
3416 // Code reference:
3417 // https://github.com/mstorsjo/llvm-mingw/blob/a1f6413e5c21fd74b64137b56167f4fba500d1d8/wrappers/clang-target-wrapper.sh#L31
3418 if !cfg!(windows) && target.os == "windows" && is_llvm_mingw_wrapper(&tool.path) {
3419 tool.has_internal_target_arg = true;
3420 }
3421
3422 // If we found `cl.exe` in our environment, the tool we're returning is
3423 // an MSVC-like tool, *and* no env vars were set then set env vars for
3424 // the tool that we're returning.
3425 //
3426 // Env vars are needed for things like `link.exe` being put into PATH as
3427 // well as header include paths sometimes. These paths are automatically
3428 // included by default but if the `CC` or `CXX` env vars are set these
3429 // won't be used. This'll ensure that when the env vars are used to
3430 // configure for invocations like `clang-cl` we still get a "works out
3431 // of the box" experience.
3432 if let Some(cl_exe) = cl_exe {
3433 if tool.family == (ToolFamily::Msvc { clang_cl: true })
3434 && tool.env.is_empty()
3435 && target.env == "msvc"
3436 {
3437 for (k, v) in cl_exe.env.iter() {
3438 tool.env.push((k.to_owned(), v.to_owned()));
3439 }
3440 }
3441 }
3442
3443 if target.env == "msvc" && tool.family == ToolFamily::Gnu {
3444 self.cargo_output
3445 .print_warning(&"GNU compiler is not supported for this target");
3446 }
3447
3448 if target.abi == "pauthtest" {
3449 match tool.family {
3450 ToolFamily::Clang { .. } => {}
3451 _ => {
3452 return Err(Error::new(
3453 ErrorKind::ToolNotFound,
3454 format!(
3455 "target '{}' requires a Clang-based toolchain, but found {:?} ({})",
3456 raw_target,
3457 tool.family,
3458 tool.path.display()
3459 ),
3460 ));
3461 }
3462 }
3463 }
3464
3465 Ok(tool)
3466 }
3467
3468 /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
3469 fn rustc_wrapper_fallback(&self) -> Option<Cow<'_, OsStr>> {
3470 // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
3471 // is defined and is a build accelerator that is compatible with
3472 // C/C++ compilers (e.g. sccache)
3473 const VALID_WRAPPERS: &[&str] = &["sccache", "cachepot", "buildcache", "kache"];
3474
3475 let rustc_wrapper = cargo_env_var_os("RUSTC_WRAPPER")?;
3476 let wrapper_path = Path::new(&rustc_wrapper);
3477 let wrapper_stem = wrapper_path.file_stem()?;
3478
3479 if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) {
3480 Some(Cow::Owned(rustc_wrapper))
3481 } else {
3482 None
3483 }
3484 }
3485
3486 /// Returns compiler path, optional modifier name from whitelist, and arguments vec
3487 fn env_tool(&self, name: &str) -> Option<(PathBuf, Option<Cow<'_, OsStr>>, Vec<String>)> {
3488 let tool = self.getenv_with_target_prefixes(name).ok()?;
3489 let tool = tool.to_string_lossy();
3490 let tool = tool.trim();
3491
3492 if tool.is_empty() {
3493 return None;
3494 }
3495
3496 // If this is an exact path on the filesystem we don't want to do any
3497 // interpretation at all, just pass it on through. This'll hopefully get
3498 // us to support spaces-in-paths.
3499 if let Some(exe) = check_exe(Path::new(tool).into()) {
3500 return Some((exe, self.rustc_wrapper_fallback(), Vec::new()));
3501 }
3502
3503 // Ok now we want to handle a couple of scenarios. We'll assume from
3504 // here on out that spaces are splitting separate arguments. Two major
3505 // features we want to support are:
3506 //
3507 // CC='sccache cc'
3508 //
3509 // aka using `sccache` or any other wrapper/caching-like-thing for
3510 // compilations. We want to know what the actual compiler is still,
3511 // though, because our `Tool` API support introspection of it to see
3512 // what compiler is in use.
3513 //
3514 // additionally we want to support
3515 //
3516 // CC='cc -flag'
3517 //
3518 // where the CC env var is used to also pass default flags to the C
3519 // compiler.
3520 //
3521 // It's true that everything here is a bit of a pain, but apparently if
3522 // you're not literally make or bash then you get a lot of bug reports.
3523 let mut known_wrappers = vec![
3524 "ccache",
3525 "distcc",
3526 "sccache",
3527 "icecc",
3528 "cachepot",
3529 "buildcache",
3530 "kache",
3531 ];
3532 let custom_wrapper = self.get_env("CC_KNOWN_WRAPPER_CUSTOM");
3533 if custom_wrapper.is_some() {
3534 known_wrappers.push(custom_wrapper.as_deref().unwrap().to_str().unwrap());
3535 }
3536
3537 let mut parts = tool.split_whitespace();
3538 let maybe_wrapper = parts.next()?;
3539
3540 let file_stem = Path::new(maybe_wrapper).file_stem()?.to_str()?;
3541 if known_wrappers.contains(&file_stem) {
3542 if let Some(compiler) = parts.next() {
3543 return Some((
3544 compiler.into(),
3545 Some(Cow::Owned(maybe_wrapper.into())),
3546 parts.map(|s| s.to_string()).collect(),
3547 ));
3548 }
3549 }
3550
3551 Some((
3552 maybe_wrapper.into(),
3553 self.rustc_wrapper_fallback(),
3554 parts.map(|s| s.to_string()).collect(),
3555 ))
3556 }
3557
3558 /// Returns the C++ standard library:
3559 /// 1. If [`cpp_link_stdlib`](cc::Build::cpp_link_stdlib) is set, uses its value.
3560 /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value.
3561 /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
3562 /// `None` for MSVC and `stdc++` for anything else.
3563 fn get_cpp_link_stdlib(&self) -> Result<Option<Cow<'_, Path>>, Error> {
3564 match &self.cpp_link_stdlib {
3565 Some(s) => Ok(s.as_deref().map(Path::new).map(Cow::Borrowed)),
3566 None => {
3567 if let Ok(stdlib) = self.getenv_with_target_prefixes("CXXSTDLIB") {
3568 if stdlib.is_empty() {
3569 Ok(None)
3570 } else {
3571 Ok(Some(Cow::Owned(Path::new(&stdlib).to_owned())))
3572 }
3573 } else {
3574 let target = self.get_target()?;
3575 if target.env == "msvc" {
3576 Ok(None)
3577 } else if target.vendor == "apple"
3578 || target.os == "freebsd"
3579 || target.os == "openbsd"
3580 || target.os == "aix"
3581 || (target.os == "linux" && target.env == "ohos")
3582 || target.os == "wasi"
3583 || target.abi == "pauthtest"
3584 {
3585 Ok(Some(Cow::Borrowed(Path::new("c++"))))
3586 } else if target.os == "android" {
3587 Ok(Some(Cow::Borrowed(Path::new("c++_shared"))))
3588 } else {
3589 Ok(Some(Cow::Borrowed(Path::new("stdc++"))))
3590 }
3591 }
3592 }
3593 }
3594 }
3595
3596 /// Get the archiver (ar) that's in use for this configuration.
3597 ///
3598 /// You can use [`Command::get_program`] to get just the path to the command.
3599 ///
3600 /// This method will take into account all configuration such as debug
3601 /// information, optimization level, include directories, defines, etc.
3602 /// Additionally, the compiler binary in use follows the standard
3603 /// conventions for this path, e.g. looking at the explicitly set compiler,
3604 /// environment variables (a number of which are inspected here), and then
3605 /// falling back to the default configuration.
3606 ///
3607 /// # Panics
3608 ///
3609 /// Panics if an error occurred while determining the architecture.
3610 pub fn get_archiver(&self) -> Command {
3611 match self.try_get_archiver() {
3612 Ok(tool) => tool,
3613 Err(e) => fail(&e.message),
3614 }
3615 }
3616
3617 /// Get the archiver that's in use for this configuration.
3618 ///
3619 /// This will return a result instead of panicking;
3620 /// see [`Self::get_archiver`] for the complete description.
3621 pub fn try_get_archiver(&self) -> Result<Command, Error> {
3622 Ok(self.try_get_archiver_and_flags()?.0)
3623 }
3624
3625 fn try_get_archiver_and_flags(&self) -> Result<(Command, PathBuf, bool), Error> {
3626 let (mut cmd, name) = self.get_base_archiver()?;
3627 let mut any_flags = false;
3628 if let Some(flags) = self.envflags("ARFLAGS")? {
3629 any_flags = true;
3630 cmd.args(flags);
3631 }
3632 for flag in &self.ar_flags {
3633 any_flags = true;
3634 cmd.arg(&**flag);
3635 }
3636 Ok((cmd, name, any_flags))
3637 }
3638
3639 fn get_base_archiver(&self) -> Result<(Command, PathBuf), Error> {
3640 if let Some(ref a) = self.archiver {
3641 let archiver = &**a;
3642 return Ok((self.cmd(archiver), archiver.into()));
3643 }
3644
3645 self.get_base_archiver_variant("AR", "ar")
3646 }
3647
3648 /// Get the ranlib that's in use for this configuration.
3649 ///
3650 /// You can use [`Command::get_program`] to get just the path to the command.
3651 ///
3652 /// This method will take into account all configuration such as debug
3653 /// information, optimization level, include directories, defines, etc.
3654 /// Additionally, the compiler binary in use follows the standard
3655 /// conventions for this path, e.g. looking at the explicitly set compiler,
3656 /// environment variables (a number of which are inspected here), and then
3657 /// falling back to the default configuration.
3658 ///
3659 /// # Panics
3660 ///
3661 /// Panics if an error occurred while determining the architecture.
3662 pub fn get_ranlib(&self) -> Command {
3663 match self.try_get_ranlib() {
3664 Ok(tool) => tool,
3665 Err(e) => fail(&e.message),
3666 }
3667 }
3668
3669 /// Get the ranlib that's in use for this configuration.
3670 ///
3671 /// This will return a result instead of panicking;
3672 /// see [`Self::get_ranlib`] for the complete description.
3673 pub fn try_get_ranlib(&self) -> Result<Command, Error> {
3674 let mut cmd = self.get_base_ranlib()?;
3675 if let Some(flags) = self.envflags("RANLIBFLAGS")? {
3676 cmd.args(flags);
3677 }
3678 Ok(cmd)
3679 }
3680
3681 fn get_base_ranlib(&self) -> Result<Command, Error> {
3682 if let Some(ref r) = self.ranlib {
3683 return Ok(self.cmd(&**r));
3684 }
3685
3686 Ok(self.get_base_archiver_variant("RANLIB", "ranlib")?.0)
3687 }
3688
3689 fn get_base_archiver_variant(
3690 &self,
3691 env: &str,
3692 tool: &str,
3693 ) -> Result<(Command, PathBuf), Error> {
3694 let target = self.get_target()?;
3695 let mut name = PathBuf::new();
3696 let tool_opt: Option<Command> = self
3697 .env_tool(env)
3698 .map(|(tool, _wrapper, args)| {
3699 name.clone_from(&tool);
3700 let mut cmd = self.cmd(tool);
3701 cmd.args(args);
3702 cmd
3703 })
3704 .or_else(|| {
3705 if target.os == "emscripten" {
3706 // Windows use bat files so we have to be a bit more specific
3707 if cfg!(windows) {
3708 let mut cmd = self.cmd("cmd");
3709 name = format!("em{tool}.bat").into();
3710 cmd.arg("/c").arg(&name);
3711 Some(cmd)
3712 } else {
3713 name = format!("em{tool}").into();
3714 Some(self.cmd(&name))
3715 }
3716 } else if target.arch == "wasm32" || target.arch == "wasm64" {
3717 // Formally speaking one should be able to use this approach,
3718 // parsing -print-search-dirs output, to cover all clang targets,
3719 // including Android SDKs and other cross-compilation scenarios...
3720 // And even extend it to gcc targets by searching for "ar" instead
3721 // of "llvm-ar"...
3722 let compiler = self.get_base_compiler().ok()?;
3723 if compiler.is_like_clang() {
3724 name = format!("llvm-{tool}").into();
3725 self.search_programs(&compiler.path, &name, &self.cargo_output)
3726 .map(|name| self.cmd(name))
3727 } else {
3728 None
3729 }
3730 } else {
3731 None
3732 }
3733 });
3734
3735 let tool = match tool_opt {
3736 Some(t) => t,
3737 None => {
3738 if target.os == "android" {
3739 name = format!("llvm-{tool}").into();
3740 // This probe decides which archiver the build uses, so it has
3741 // to run in the environment the build was configured with: a
3742 // bare name resolves through `Build::env`'s `PATH`, not the
3743 // ambient one.
3744 let mut probe = Command::new(&name);
3745 probe.arg("--version").set_ar_detection_env(&self.env);
3746 match probe.status() {
3747 Ok(status) if status.success() => (),
3748 _ => {
3749 // FIXME: Use parsed target.
3750 let raw_target = self.get_raw_target()?;
3751 name = format!("{}-{}", raw_target.replace("armv7", "arm"), tool).into()
3752 }
3753 }
3754 self.cmd(&name)
3755 } else if target.env == "msvc" {
3756 // NOTE: There isn't really a ranlib on msvc, so arguably we should return
3757 // `None` somehow here. But in general, callers will already have to be aware
3758 // of not running ranlib on Windows anyway, so it feels okay to return lib.exe
3759 // here.
3760
3761 let compiler = self.get_base_compiler()?;
3762 let lib = if compiler.family == (ToolFamily::Msvc { clang_cl: true }) {
3763 self.search_programs(
3764 &compiler.path,
3765 Path::new("llvm-lib"),
3766 &self.cargo_output,
3767 )
3768 .or_else(|| {
3769 // See if there is 'llvm-lib' next to 'clang-cl'
3770 if let Some(mut cmd) = self.which(&compiler.path, None) {
3771 cmd.pop();
3772 cmd.push("llvm-lib");
3773 self.which(&cmd, None)
3774 } else {
3775 None
3776 }
3777 })
3778 } else {
3779 None
3780 };
3781
3782 if let Some(lib) = lib {
3783 name = lib;
3784 self.cmd(&name)
3785 } else {
3786 name = PathBuf::from("lib.exe");
3787 let mut cmd = match self.find_msvc_tools_find(&target, "lib.exe") {
3788 Some(t) => t,
3789 None => self.cmd("lib.exe"),
3790 };
3791 if target.full_arch == "arm64ec" {
3792 cmd.arg("/machine:arm64ec");
3793 }
3794 cmd
3795 }
3796 } else if target.os == "illumos" {
3797 // The default 'ar' on illumos uses a non-standard flags,
3798 // but the OS comes bundled with a GNU-compatible variant.
3799 //
3800 // Use the GNU-variant to match other Unix systems.
3801 name = format!("g{tool}").into();
3802 self.cmd(&name)
3803 } else if target.os == "vxworks" {
3804 name = format!("wr-{tool}").into();
3805 self.cmd(&name)
3806 } else if target.os == "nto" || target.os == "qnx" {
3807 // Ref: https://www.qnx.com/developers/docs/8.0/com.qnx.doc.neutrino.utilities/topic/a/ar.html
3808 name = match target.full_arch {
3809 "i686" | "i586" => format!("ntox86-{tool}").into(),
3810 "x86" | "aarch64" | "x86_64" => {
3811 format!("nto{}-{}", target.arch, tool).into()
3812 }
3813 _ => {
3814 return Err(Error::new(
3815 ErrorKind::InvalidTarget,
3816 format!("Unknown architecture for Neutrino QNX: {}", target.arch),
3817 ))
3818 }
3819 };
3820 self.cmd(&name)
3821 } else if self.get_is_cross_compile()? {
3822 match self.prefix_for_target(&self.get_raw_target()?) {
3823 Some(prefix) => {
3824 // GCC uses $target-gcc-ar, whereas binutils uses $target-ar -- try both.
3825 // Prefer -ar if it exists, as builds of `-gcc-ar` have been observed to be
3826 // outright broken (such as when targeting freebsd with `--disable-lto`
3827 // toolchain where the archiver attempts to load the LTO plugin anyway but
3828 // fails to find one).
3829 //
3830 // The same applies to ranlib.
3831 let chosen = ["", "-gcc"]
3832 .iter()
3833 .filter_map(|infix| {
3834 let target_p = format!("{prefix}{infix}-{tool}");
3835 let status = Command::new(&target_p)
3836 .arg("--version")
3837 .stdin(Stdio::null())
3838 .stdout(Stdio::null())
3839 .stderr(Stdio::null())
3840 .status()
3841 .ok()?;
3842 status.success().then_some(target_p)
3843 })
3844 .next()
3845 .unwrap_or_else(|| tool.to_string());
3846 name = chosen.into();
3847 self.cmd(&name)
3848 }
3849 None => {
3850 name = tool.into();
3851 self.cmd(&name)
3852 }
3853 }
3854 } else {
3855 name = tool.into();
3856 self.cmd(&name)
3857 }
3858 }
3859 };
3860
3861 Ok((tool, name))
3862 }
3863
3864 // FIXME: Use parsed target instead of raw target.
3865 fn prefix_for_target(&self, target: &str) -> Option<Cow<'static, str>> {
3866 // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
3867 self.get_env("CROSS_COMPILE")
3868 .as_deref()
3869 .map(|s| s.to_string_lossy().trim_end_matches('-').to_owned())
3870 .map(Cow::Owned)
3871 .or_else(|| {
3872 // Put aside RUSTC_LINKER's prefix to be used as second choice, after CROSS_COMPILE
3873 cargo_env_var_os("RUSTC_LINKER").and_then(|var| {
3874 var.to_string_lossy()
3875 .strip_suffix("-gcc")
3876 .map(str::to_string)
3877 .map(Cow::Owned)
3878 })
3879 })
3880 .or_else(|| {
3881 match target {
3882 // Note: there is no `aarch64-pc-windows-gnu` target, only `-gnullvm`
3883 "aarch64-pc-windows-gnullvm" => Some("aarch64-w64-mingw32"),
3884 "aarch64-uwp-windows-gnu" => Some("aarch64-w64-mingw32"),
3885 "aarch64-unknown-helenos" => Some("aarch64-helenos"),
3886 "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
3887 "aarch64_be-unknown-linux-gnu" => Some("aarch64_be-linux-gnu"),
3888 "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
3889 "aarch64-unknown-linux-relibc" => Some("aarch64-linux-relibc"),
3890 "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
3891 "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3892 "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3893 "armv5te-unknown-helenos-eabi" => Some("arm-helenos"),
3894 "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3895 "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
3896 "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3897 "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
3898 "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3899 "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
3900 "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
3901 "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3902 "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3903 "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3904 "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3905 "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3906 "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3907 "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3908 "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3909 "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3910 "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
3911 "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"),
3912 "i586-unknown-linux-musl" => Some("musl"),
3913 "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
3914 "i686-pc-windows-gnullvm" => Some("i686-w64-mingw32"),
3915 "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
3916 "i686-unknown-helenos" => Some("i686-helenos"),
3917 "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3918 "i686-linux-gnu",
3919 "x86_64-linux-gnu", // transparently support gcc-multilib
3920 ]), // explicit None if not found, so caller knows to fall back
3921 "i686-unknown-linux-musl" => Some("musl"),
3922 "i686-unknown-netbsd" => Some("i486--netbsdelf"),
3923 "loongarch64-unknown-linux-gnu" => Some("loongarch64-linux-gnu"),
3924 "m68k-unknown-linux-gnu" => Some("m68k-linux-gnu"),
3925 "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
3926 "mips-unknown-linux-musl" => Some("mips-linux-musl"),
3927 "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
3928 "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"),
3929 "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
3930 "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
3931 "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
3932 "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
3933 "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
3934 "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
3935 "powerpc-unknown-helenos" => Some("ppc-helenos"),
3936 "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
3937 "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
3938 "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
3939 "powerpc64-unknown-linux-gnu" => Some("powerpc64-linux-gnu"),
3940 "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
3941 "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[
3942 "riscv32-unknown-elf",
3943 "riscv64-unknown-elf",
3944 "riscv-none-embed",
3945 ]),
3946 "riscv32im-unknown-none-elf" => self.find_working_gnu_prefix(&[
3947 "riscv32-unknown-elf",
3948 "riscv64-unknown-elf",
3949 "riscv-none-embed",
3950 ]),
3951 "riscv32imac-esp-espidf" => Some("riscv32-esp-elf"),
3952 "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3953 "riscv32-unknown-elf",
3954 "riscv64-unknown-elf",
3955 "riscv-none-embed",
3956 ]),
3957 "riscv32imafc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3958 "riscv32-unknown-elf",
3959 "riscv64-unknown-elf",
3960 "riscv-none-embed",
3961 ]),
3962 "riscv32imac-unknown-xous-elf" => self.find_working_gnu_prefix(&[
3963 "riscv32-unknown-elf",
3964 "riscv64-unknown-elf",
3965 "riscv-none-embed",
3966 ]),
3967 "riscv32imc-esp-espidf" => Some("riscv32-esp-elf"),
3968 "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3969 "riscv32-unknown-elf",
3970 "riscv64-unknown-elf",
3971 "riscv-none-embed",
3972 ]),
3973 "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3974 "riscv64-unknown-elf",
3975 "riscv32-unknown-elf",
3976 "riscv-none-embed",
3977 ]),
3978 "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3979 "riscv64-unknown-elf",
3980 "riscv32-unknown-elf",
3981 "riscv-none-embed",
3982 ]),
3983 "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
3984 "riscv64a23-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
3985 "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"),
3986 "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"),
3987 "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"),
3988 "riscv64gc-unknown-netbsd" => Some("riscv64--netbsd"),
3989 "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
3990 "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
3991 "sparc64-unknown-helenos" => Some("sparc64-helenos"),
3992 "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
3993 "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
3994 "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
3995 "armv4t-none-eabi" => Some("arm-none-eabi"),
3996 "armv5te-none-eabi" => Some("arm-none-eabi"),
3997 "armv6-none-eabi" => Some("arm-none-eabi"),
3998 "armv6-none-eabihf" => Some("arm-none-eabi"),
3999 "armv7a-none-eabi" => Some("arm-none-eabi"),
4000 "armv7a-none-eabihf" => Some("arm-none-eabi"),
4001 "armebv7r-none-eabi" => Some("arm-none-eabi"),
4002 "armebv7r-none-eabihf" => Some("arm-none-eabi"),
4003 "armv7r-none-eabi" => Some("arm-none-eabi"),
4004 "armv7r-none-eabihf" => Some("arm-none-eabi"),
4005 "armv8r-none-eabihf" => Some("arm-none-eabi"),
4006 "thumbv4t-none-eabi" => Some("arm-none-eabi"),
4007 "thumbv5te-none-eabi" => Some("arm-none-eabi"),
4008 "thumbv6-none-eabi" => Some("arm-none-eabi"),
4009 "thumbv7a-none-eabi" => Some("arm-none-eabi"),
4010 "thumbv7a-none-eabihf" => Some("arm-none-eabi"),
4011 "thumbv7r-none-eabi" => Some("arm-none-eabi"),
4012 "thumbv7r-none-eabihf" => Some("arm-none-eabi"),
4013 "thumbv8r-none-eabihf" => Some("arm-none-eabi"),
4014 "thumbv6m-none-eabi" => Some("arm-none-eabi"),
4015 "thumbv7em-none-eabi" => Some("arm-none-eabi"),
4016 "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
4017 "thumbv7m-none-eabi" => Some("arm-none-eabi"),
4018 "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
4019 "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
4020 "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
4021 "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
4022 "x86_64-pc-windows-gnullvm" => Some("x86_64-w64-mingw32"),
4023 "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
4024 "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
4025 "x86_64-unknown-helenos" => Some("amd64-helenos"),
4026 "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
4027 "x86_64-linux-gnu", // rustfmt wrap
4028 ]), // explicit None if not found, so caller knows to fall back
4029 "x86_64-unknown-linux-musl" => {
4030 self.find_working_gnu_prefix(&["x86_64-linux-musl", "musl"])
4031 }
4032 "x86_64-unknown-linux-relibc" => {
4033 self.find_working_gnu_prefix(&["x86_64-linux-relibc", "relibc"])
4034 }
4035 "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
4036 "xtensa-esp32-espidf"
4037 | "xtensa-esp32-none-elf"
4038 | "xtensa-esp32s2-espidf"
4039 | "xtensa-esp32s2-none-elf"
4040 | "xtensa-esp32s3-espidf"
4041 | "xtensa-esp32s3-none-elf" => Some("xtensa-esp-elf"),
4042 _ => None,
4043 }
4044 .map(Cow::Borrowed)
4045 })
4046 }
4047
4048 /// Some platforms have multiple, compatible, canonical prefixes. Look through
4049 /// each possible prefix for a compiler that exists and return it. The prefixes
4050 /// should be ordered from most-likely to least-likely.
4051 fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> {
4052 let suffix = if self.cpp { "-g++" } else { "-gcc" };
4053 let extension = std::env::consts::EXE_SUFFIX;
4054
4055 // Loop through PATH entries searching for each toolchain. This ensures that we
4056 // are more likely to discover the toolchain early on, because chances are good
4057 // that the desired toolchain is in one of the higher-priority paths.
4058 self.get_env("PATH")
4059 .as_ref()
4060 .and_then(|path_entries| {
4061 env::split_paths(path_entries).find_map(|path_entry| {
4062 for prefix in prefixes {
4063 let target_compiler = format!("{prefix}{suffix}{extension}");
4064 if path_entry.join(&target_compiler).exists() {
4065 return Some(prefix);
4066 }
4067 }
4068 None
4069 })
4070 })
4071 .copied()
4072 // If no toolchain was found, provide the first toolchain that was passed in.
4073 // This toolchain has been shown not to exist, however it will appear in the
4074 // error that is shown to the user which should make it easier to search for
4075 // where it should be obtained.
4076 .or_else(|| prefixes.first().copied())
4077 }
4078
4079 fn get_target(&self) -> Result<TargetInfo<'_>, Error> {
4080 match &self.target {
4081 Some(t) if Some(OsStr::new(&**t)) != cargo_env_var_os("TARGET").as_deref() => {
4082 TargetInfo::from_rustc_target(t)
4083 }
4084 // Fetch target information from environment if not set, or if the
4085 // target was the same as the TARGET environment variable, in
4086 // case the user did `build.target(&env::var("TARGET").unwrap())`.
4087 _ => self
4088 .build_cache
4089 .target_info_parser
4090 .parse_from_cargo_environment_variables(),
4091 }
4092 }
4093
4094 fn get_raw_target(&self) -> Result<Cow<'_, str>, Error> {
4095 match &self.target {
4096 Some(t) => Ok(Cow::Borrowed(t)),
4097 None => cargo_env_var("TARGET").map(Cow::Owned),
4098 }
4099 }
4100
4101 fn get_is_cross_compile(&self) -> Result<bool, Error> {
4102 let target = self.get_raw_target()?;
4103 let host: Cow<'_, str> = match &self.host {
4104 Some(h) => Cow::Borrowed(h),
4105 None => Cow::Owned(cargo_env_var("HOST")?),
4106 };
4107 Ok(host != target)
4108 }
4109
4110 fn get_opt_level(&self) -> Result<Cow<'_, str>, Error> {
4111 match &self.opt_level {
4112 Some(ol) => Ok(Cow::Borrowed(ol)),
4113 None => cargo_env_var("OPT_LEVEL").map(Cow::Owned),
4114 }
4115 }
4116
4117 /// Returns true if *any* debug info is enabled.
4118 ///
4119 /// [`get_debug_str`] provides more detail.
4120 fn get_debug(&self) -> bool {
4121 match self.get_debug_str() {
4122 Err(_) => false,
4123 Ok(d) => match &*d {
4124 // From https://doc.rust-lang.org/cargo/reference/profiles.html#debug
4125 "" | "0" | "false" | "none" => false,
4126 _ => true,
4127 },
4128 }
4129 }
4130
4131 fn get_debug_str(&self) -> Result<Cow<'_, str>, Error> {
4132 match &self.debug {
4133 Some(d) => Ok(Cow::Borrowed(d)),
4134 None => cargo_env_var("DEBUG").map(Cow::Owned),
4135 }
4136 }
4137
4138 fn get_shell_escaped_flags(&self) -> bool {
4139 self.shell_escaped_flags
4140 .unwrap_or_else(|| self.get_env_boolean("CC_SHELL_ESCAPED_FLAGS"))
4141 }
4142
4143 fn get_dwarf_version(&self) -> Option<u32> {
4144 // Tentatively matches the DWARF version defaults as of rustc 1.62.
4145 let target = self.get_target().ok()?;
4146 if matches!(
4147 target.os,
4148 "android" | "dragonfly" | "freebsd" | "netbsd" | "openbsd"
4149 ) || target.vendor == "apple"
4150 || (target.os == "windows" && target.env == "gnu")
4151 {
4152 Some(2)
4153 } else if target.os == "linux" {
4154 Some(4)
4155 } else {
4156 None
4157 }
4158 }
4159
4160 fn get_force_frame_pointer(&self) -> bool {
4161 self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
4162 }
4163
4164 fn get_out_dir(&self) -> Result<Cow<'_, Path>, Error> {
4165 match &self.out_dir {
4166 Some(p) => Ok(Cow::Borrowed(&**p)),
4167 None => cargo_env_var_os("OUT_DIR")
4168 .map(PathBuf::from)
4169 .map(Cow::Owned)
4170 .ok_or_else(|| {
4171 Error::new(
4172 ErrorKind::EnvVarNotFound,
4173 "Environment variable OUT_DIR not defined.",
4174 )
4175 }),
4176 }
4177 }
4178
4179 /// Look up an environment variable, and tell Cargo that we used it.
4180 fn get_env(&self, v: &str) -> Option<OsString> {
4181 // Excluding `PATH` prevents spurious rebuilds on Windows, see
4182 // <https://github.com/rust-lang/cc-rs/pull/1215> for details.
4183 if self.emit_rerun_if_env_changed && v != "PATH" {
4184 self.cargo_output
4185 .print_metadata(&format_args!("cargo:rerun-if-env-changed={v}"));
4186 }
4187 #[allow(clippy::disallowed_methods)] // We emit rerun-if-env-changed above
4188 let r = env::var_os(v);
4189 self.cargo_output.print_metadata(&format_args!(
4190 "{} = {}",
4191 v,
4192 OptionOsStrDisplay(r.as_deref())
4193 ));
4194 r
4195 }
4196
4197 /// Look up an environment variable that's allowed to be overwritten by
4198 /// [`Build::env`].
4199 ///
4200 /// This is useful for environment variables that the compiler could
4201 /// reasonably read, such as `SDKROOT` and `WASI_SDK_PATH` - for these, we
4202 /// generally want to allow build scripts to overwrite them.
4203 ///
4204 /// On the other hand, we don't want to allow overwriting environment
4205 /// variables that are `CC`-specific such as `CC_FORCE_DISABLE`
4206 /// (`Build::env` applies to child processes, not to `cc` itself).
4207 fn get_env_overridable(&self, key: &str) -> Option<Cow<'_, OsStr>> {
4208 // Try to look up in overrides first.
4209 if let Some((_key, val)) = self.env.iter().find(|(k, _)| k.as_ref() == key) {
4210 return Some(Cow::Borrowed(&**val));
4211 }
4212
4213 // If not found in overrides, look up from environment.
4214 self.get_env(key).map(Cow::Owned)
4215 }
4216
4217 /// Get boolean flag that is either true or false.
4218 ///
4219 /// Used for `CC_*`-style flags.
4220 fn get_env_boolean(&self, key: &str) -> bool {
4221 match self.get_env(key) {
4222 // Set -> `true`, unless set to `""`, `"0"`, `"no"` `"false"`
4223 Some(s) => &*s != "0" && &*s != "false" && &*s != "no" && !s.is_empty(),
4224 // Not set -> default to `false`.
4225 None => false,
4226 }
4227 }
4228
4229 /// The list of environment variables to check for a given env, in order of priority.
4230 fn target_envs(&self, env: &str) -> Result<[String; 4], Error> {
4231 let target = self.get_raw_target()?;
4232 let kind = if self.get_is_cross_compile()? {
4233 "TARGET"
4234 } else {
4235 "HOST"
4236 };
4237 let target_u = target.replace(['-', '.'], "_");
4238
4239 Ok([
4240 format!("{env}_{target}"),
4241 format!("{env}_{target_u}"),
4242 format!("{kind}_{env}"),
4243 env.to_string(),
4244 ])
4245 }
4246
4247 /// Get a single-valued environment variable with target variants.
4248 fn getenv_with_target_prefixes(&self, env: &str) -> Result<OsString, Error> {
4249 // Take from first environment variable in the environment.
4250 let res = self
4251 .target_envs(env)?
4252 .iter()
4253 .filter_map(|env| self.get_env(env))
4254 .next();
4255
4256 match res {
4257 Some(res) => Ok(res),
4258 None => Err(Error::new(
4259 ErrorKind::EnvVarNotFound,
4260 format!("could not find environment variable {env}"),
4261 )),
4262 }
4263 }
4264
4265 /// Get values from CFLAGS-style environment variable.
4266 fn envflags(&self, env: &str) -> Result<Option<Vec<String>>, Error> {
4267 // Collect from all environment variables, in reverse order as in
4268 // `getenv_with_target_prefixes` precedence (so that `CFLAGS_$TARGET`
4269 // can override flags in `TARGET_CFLAGS`, which overrides those in
4270 // `CFLAGS`).
4271 let mut any_set = false;
4272 let mut res = vec![];
4273 for env in self.target_envs(env)?.iter().rev() {
4274 if let Some(var) = self.get_env(env) {
4275 any_set = true;
4276
4277 let var = var.to_string_lossy();
4278 if self.get_shell_escaped_flags() {
4279 res.extend(Shlex::new(&var));
4280 } else {
4281 res.extend(var.split_ascii_whitespace().map(ToString::to_string));
4282 }
4283 }
4284 }
4285
4286 Ok(if any_set { Some(res) } else { None })
4287 }
4288
4289 /// Returns true if `cc` has been disabled by `CC_FORCE_DISABLE`.
4290 fn is_disabled(&self) -> bool {
4291 self.get_env_boolean("CC_FORCE_DISABLE")
4292 }
4293
4294 fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
4295 let target = self.get_target()?;
4296 if cfg!(target_os = "macos") && target.os == "macos" {
4297 // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
4298 // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
4299 // although this is apparently ignored when using the linker at "/usr/bin/ld".
4300 cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET");
4301 }
4302 Ok(())
4303 }
4304
4305 fn apple_sdk_root_inner(&self, sdk: &str) -> Result<Cow<'_, OsStr>, Error> {
4306 // Code copied from rustc's compiler/rustc_codegen_ssa/src/back/link.rs.
4307 if let Some(sdkroot) = self.get_env_overridable("SDKROOT") {
4308 let p = Path::new(&sdkroot);
4309 let does_sdkroot_contain = |strings: &[&str]| {
4310 let sdkroot_str = p.to_string_lossy();
4311 strings.iter().any(|s| sdkroot_str.contains(s))
4312 };
4313 match sdk {
4314 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
4315 "appletvos"
4316 if does_sdkroot_contain(&["TVSimulator.platform", "MacOSX.platform"]) => {}
4317 "appletvsimulator"
4318 if does_sdkroot_contain(&["TVOS.platform", "MacOSX.platform"]) => {}
4319 "iphoneos"
4320 if does_sdkroot_contain(&["iPhoneSimulator.platform", "MacOSX.platform"]) => {}
4321 "iphonesimulator"
4322 if does_sdkroot_contain(&["iPhoneOS.platform", "MacOSX.platform"]) => {}
4323 "macosx10.15"
4324 if does_sdkroot_contain(&["iPhoneOS.platform", "iPhoneSimulator.platform"]) => {
4325 }
4326 "watchos"
4327 if does_sdkroot_contain(&["WatchSimulator.platform", "MacOSX.platform"]) => {}
4328 "watchsimulator"
4329 if does_sdkroot_contain(&["WatchOS.platform", "MacOSX.platform"]) => {}
4330 "xros" if does_sdkroot_contain(&["XRSimulator.platform", "MacOSX.platform"]) => {}
4331 "xrsimulator" if does_sdkroot_contain(&["XROS.platform", "MacOSX.platform"]) => {}
4332 // Ignore `SDKROOT` if it's not a valid path.
4333 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
4334 _ => return Ok(sdkroot),
4335 }
4336 }
4337
4338 let sdk_path = run_output(
4339 self.cmd("xcrun")
4340 .arg("--show-sdk-path")
4341 .arg("--sdk")
4342 .arg(sdk),
4343 &self.cargo_output,
4344 )?;
4345
4346 let Ok(sdk_path) = String::from_utf8(sdk_path) else {
4347 return Err(Error::new(
4348 ErrorKind::IOError,
4349 "Unable to determine Apple SDK path.",
4350 ));
4351 };
4352 Ok(Cow::Owned(sdk_path.trim().into()))
4353 }
4354
4355 fn apple_sdk_root(&self, target: &TargetInfo<'_>) -> Result<Arc<OsStr>, Error> {
4356 let sdk = target.apple_sdk_name();
4357
4358 if let Some(ret) = self
4359 .build_cache
4360 .apple_sdk_root_cache
4361 .read()
4362 .expect("apple_sdk_root_cache lock failed")
4363 .get(sdk)
4364 .cloned()
4365 {
4366 return Ok(ret);
4367 }
4368 let sdk_path: Arc<OsStr> = self.apple_sdk_root_inner(sdk)?.into();
4369 self.build_cache
4370 .apple_sdk_root_cache
4371 .write()
4372 .expect("apple_sdk_root_cache lock failed")
4373 .insert(sdk.into(), sdk_path.clone());
4374 Ok(sdk_path)
4375 }
4376
4377 fn apple_deployment_target(&self, target: &TargetInfo<'_>) -> Arc<str> {
4378 let sdk = target.apple_sdk_name();
4379 if let Some(ret) = self
4380 .build_cache
4381 .apple_versions_cache
4382 .read()
4383 .expect("apple_versions_cache lock failed")
4384 .get(sdk)
4385 .cloned()
4386 {
4387 return ret;
4388 }
4389
4390 let default_deployment_from_sdk = || -> Option<Arc<str>> {
4391 let version = run_output(
4392 self.cmd("xcrun")
4393 .arg("--show-sdk-version")
4394 .arg("--sdk")
4395 .arg(sdk),
4396 &self.cargo_output,
4397 )
4398 .ok()?;
4399
4400 Some(Arc::from(std::str::from_utf8(&version).ok()?.trim()))
4401 };
4402
4403 let deployment_from_env = |name: &str| -> Option<Arc<str>> {
4404 self.get_env_overridable(name)?.to_str().map(Arc::from)
4405 };
4406
4407 // Determines if the acquired deployment target is too low to support modern C++ on some Apple platform.
4408 //
4409 // A long time ago they used libstdc++, but since macOS 10.9 and iOS 7 libc++ has been the library the SDKs provide to link against.
4410 // If a `cc`` config wants to use C++, we round up to these versions as the baseline.
4411 let maybe_cpp_version_baseline = |deployment_target_ver: Arc<str>| -> Option<Arc<str>> {
4412 if !self.cpp {
4413 return Some(deployment_target_ver);
4414 }
4415
4416 let mut deployment_target = deployment_target_ver
4417 .split('.')
4418 .map(|v| v.parse::<u32>().expect("integer version"));
4419
4420 match target.os {
4421 "macos" => {
4422 let major = deployment_target.next().unwrap_or(0);
4423 let minor = deployment_target.next().unwrap_or(0);
4424
4425 // If below 10.9, we ignore it and let the SDK's target definitions handle it.
4426 if major == 10 && minor < 9 {
4427 self.cargo_output.print_warning(&format_args!(
4428 "macOS deployment target ({deployment_target_ver}) too low, it will be increased"
4429 ));
4430 return None;
4431 }
4432 }
4433 "ios" => {
4434 let major = deployment_target.next().unwrap_or(0);
4435
4436 // If below 10.7, we ignore it and let the SDK's target definitions handle it.
4437 if major < 7 {
4438 self.cargo_output.print_warning(&format_args!(
4439 "iOS deployment target ({deployment_target_ver}) too low, it will be increased"
4440 ));
4441 return None;
4442 }
4443 }
4444 // watchOS, tvOS, visionOS, and others are all new enough that libc++ is their baseline.
4445 _ => {}
4446 }
4447
4448 // If the deployment target met or exceeded the C++ baseline
4449 Some(deployment_target_ver)
4450 };
4451
4452 // The hardcoded minimums here are subject to change in a future compiler release,
4453 // and only exist as last resort fallbacks. Don't consider them stable.
4454 // `cc` doesn't use rustc's `--print deployment-target`` because the compiler's defaults
4455 // don't align well with Apple's SDKs and other third-party libraries that require ~generally~ higher
4456 // deployment targets. rustc isn't interested in those by default though so its fine to be different here.
4457 //
4458 // If no explicit target is passed, `cc` defaults to the current Xcode SDK's `DefaultDeploymentTarget` for better
4459 // compatibility. This is also the crate's historical behavior and what has become a relied-on value.
4460 //
4461 // The ordering of env -> XCode SDK -> old rustc defaults is intentional for performance when using
4462 // an explicit target.
4463 let version: Arc<str> = match target.os {
4464 "macos" => deployment_from_env("MACOSX_DEPLOYMENT_TARGET")
4465 .and_then(maybe_cpp_version_baseline)
4466 .or_else(default_deployment_from_sdk)
4467 .unwrap_or_else(|| {
4468 if target.arch == "aarch64" {
4469 "11.0".into()
4470 } else {
4471 let default: Arc<str> = Arc::from("10.7");
4472 maybe_cpp_version_baseline(default.clone()).unwrap_or(default)
4473 }
4474 }),
4475
4476 "ios" => deployment_from_env("IPHONEOS_DEPLOYMENT_TARGET")
4477 .and_then(maybe_cpp_version_baseline)
4478 .or_else(default_deployment_from_sdk)
4479 .unwrap_or_else(|| "7.0".into()),
4480
4481 "watchos" => deployment_from_env("WATCHOS_DEPLOYMENT_TARGET")
4482 .or_else(default_deployment_from_sdk)
4483 .unwrap_or_else(|| "5.0".into()),
4484
4485 "tvos" => deployment_from_env("TVOS_DEPLOYMENT_TARGET")
4486 .or_else(default_deployment_from_sdk)
4487 .unwrap_or_else(|| "9.0".into()),
4488
4489 "visionos" => deployment_from_env("XROS_DEPLOYMENT_TARGET")
4490 .or_else(default_deployment_from_sdk)
4491 .unwrap_or_else(|| "1.0".into()),
4492
4493 os => unreachable!("unknown Apple OS: {}", os),
4494 };
4495
4496 self.build_cache
4497 .apple_versions_cache
4498 .write()
4499 .expect("apple_versions_cache lock failed")
4500 .insert(sdk.into(), version.clone());
4501
4502 version
4503 }
4504
4505 fn wasm_musl_sysroot(&self) -> Result<OsString, Error> {
4506 if let Some(musl_sysroot_path) = self.get_env("WASM_MUSL_SYSROOT") {
4507 Ok(musl_sysroot_path)
4508 } else {
4509 Err(Error::new(
4510 ErrorKind::EnvVarNotFound,
4511 "Environment variable WASM_MUSL_SYSROOT not defined for wasm32. Download sysroot from GitHub & setup environment variable MUSL_SYSROOT targeting the folder.",
4512 ))
4513 }
4514 }
4515
4516 fn wasi_sysroot(&self) -> Result<OsString, Error> {
4517 if let Some(wasi_sysroot_path) = self.get_env("WASI_SYSROOT") {
4518 Ok(wasi_sysroot_path)
4519 } else {
4520 Err(Error::new(
4521 ErrorKind::EnvVarNotFound,
4522 "Environment variable WASI_SYSROOT not defined. Download sysroot from GitHub & setup environment variable WASI_SYSROOT targeting the folder.",
4523 ))
4524 }
4525 }
4526
4527 fn cuda_file_count(&self) -> usize {
4528 self.files
4529 .iter()
4530 .filter(|file| file.extension() == Some(OsStr::new("cu")))
4531 .count()
4532 }
4533
4534 fn which(&self, tool: &Path, path_entries: Option<&OsStr>) -> Option<PathBuf> {
4535 // Loop through PATH entries searching for the |tool|.
4536 let find_exe_in_path = |path_entries: &OsStr| -> Option<PathBuf> {
4537 env::split_paths(path_entries).find_map(|path_entry| check_exe(path_entry.join(tool)))
4538 };
4539
4540 // If |tool| is not just one "word," assume it's an actual path...
4541 if tool.components().count() > 1 {
4542 check_exe(PathBuf::from(tool))
4543 } else {
4544 path_entries
4545 .and_then(find_exe_in_path)
4546 .or_else(|| find_exe_in_path(&self.get_env("PATH")?))
4547 }
4548 }
4549
4550 /// search for |prog| on 'programs' path in '|cc| --print-search-dirs' output
4551 fn search_programs(
4552 &self,
4553 cc: &Path,
4554 prog: &Path,
4555 cargo_output: &CargoOutput,
4556 ) -> Option<PathBuf> {
4557 let search_dirs = run_output(
4558 self.cmd(cc).arg("--print-search-dirs"),
4559 // this doesn't concern the compilation so we always want to show warnings.
4560 cargo_output,
4561 )
4562 .ok()?;
4563 // clang driver appears to be forcing UTF-8 output even on Windows,
4564 // hence from_utf8 is assumed to be usable in all cases.
4565 let search_dirs = std::str::from_utf8(&search_dirs).ok()?;
4566 for dirs in search_dirs.split(['\r', '\n']) {
4567 if let Some(path) = dirs.strip_prefix("programs: =") {
4568 return self.which(prog, Some(OsStr::new(path)));
4569 }
4570 }
4571 None
4572 }
4573
4574 fn find_msvc_tools_find(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Command> {
4575 self.find_msvc_tools_find_tool(target, tool)
4576 .map(|c| c.to_command())
4577 }
4578
4579 fn find_msvc_tools_find_tool(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Tool> {
4580 struct BuildEnvGetter<'s>(&'s Build);
4581
4582 impl ::find_msvc_tools::EnvGetter for BuildEnvGetter<'_> {
4583 fn get_env(&self, name: &str) -> Option<::find_msvc_tools::Env> {
4584 // TODO: Should we allow overriding these with `Build::env`?
4585 // <https://github.com/rust-lang/cc-rs/issues/1688>
4586 self.0.get_env(name).map(::find_msvc_tools::Env::Owned)
4587 }
4588 }
4589
4590 if target.env != "msvc" {
4591 return None;
4592 }
4593
4594 ::find_msvc_tools::find_tool_with_env(target.full_arch, tool, &BuildEnvGetter(self))
4595 .map(Tool::from_find_msvc_tools)
4596 }
4597
4598 /// Compiling for WASI targets typically uses the [wasi-sdk] project and
4599 /// installations of wasi-sdk are typically indicated with the
4600 /// `WASI_SDK_PATH` environment variable. Check to see if that environment
4601 /// variable exists, and check to see if an appropriate compiler is located
4602 /// there. If that all passes then use that compiler by default, but
4603 /// otherwise fall back to whatever the clang default is since gcc doesn't
4604 /// have support for compiling to wasm.
4605 ///
4606 /// [wasi-sdk]: https://github.com/WebAssembly/wasi-sdk
4607 fn autodetect_wasi_compiler(&self, raw_target: &str, clang: &str) -> PathBuf {
4608 if let Some(path) = self.get_env_overridable("WASI_SDK_PATH") {
4609 let target_clang = Path::new(&path)
4610 .join("bin")
4611 .join(format!("{raw_target}-clang"));
4612 if let Some(path) = self.which(&target_clang, None) {
4613 return path;
4614 }
4615 }
4616
4617 clang.into()
4618 }
4619
4620 fn pauthtest_sysroot(&self) -> Result<OsString, Error> {
4621 if let Some(pauthtest_sysroot) = self.get_env("PAUTHTEST_SYSROOT") {
4622 Ok(pauthtest_sysroot)
4623 } else {
4624 let target = self.get_raw_target()?;
4625 Err(Error::new(
4626 ErrorKind::EnvVarNotFound,
4627 format!(
4628 "Environment variable PAUTHTEST_SYSROOT not defined for the {} target. Please consult target's platform support document for instructions on how to obtain the sysroot and then setup the environment variable PAUTHTEST_SYSROOT.",
4629 target
4630 ),
4631 ))
4632 }
4633 }
4634
4635 fn pauthtest_resource_dir(&self) -> Result<OsString, Error> {
4636 if let Some(pauthtest_resource_dir) = self.get_env("PAUTHTEST_RESOURCE_DIR") {
4637 Ok(pauthtest_resource_dir)
4638 } else {
4639 let target = self.get_raw_target()?;
4640 Err(Error::new(
4641 ErrorKind::EnvVarNotFound,
4642 format!(
4643 "Environment variable PAUTHTEST_RESOURCE_DIR not defined for the {} target. Please consult target's platform support document for instructions on how to obtain the sysroot and then setup the environment variable PAUTHTEST_RESOURCE_DIR.",
4644 target
4645 ),
4646 ))
4647 }
4648 }
4649}
4650
4651impl Default for Build {
4652 fn default() -> Build {
4653 Build::new()
4654 }
4655}
4656
4657fn fail(s: &str) -> ! {
4658 eprintln!("\n\nerror occurred in cc-rs: {s}\n\n");
4659 std::process::exit(1);
4660}
4661
4662// Use by default minimum available API level
4663// See note about naming here
4664// https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
4665static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
4666 "aarch64-linux-android21-clang",
4667 "armv7a-linux-androideabi16-clang",
4668 "i686-linux-android16-clang",
4669 "x86_64-linux-android21-clang",
4670];
4671
4672// New "standalone" C/C++ cross-compiler executables from recent Android NDK
4673// are just shell scripts that call main clang binary (from Android NDK) with
4674// proper `--target` argument.
4675//
4676// For example, armv7a-linux-androideabi16-clang passes
4677// `--target=armv7a-linux-androideabi16` to clang.
4678// So to construct proper command line check if
4679// `--target` argument would be passed or not to clang
4680fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
4681 if let Some(filename) = clang_path.file_name() {
4682 if let Some(filename_str) = filename.to_str() {
4683 if let Some(idx) = filename_str.rfind('-') {
4684 return filename_str.split_at(idx).0.contains("android");
4685 }
4686 }
4687 }
4688 false
4689}
4690
4691fn is_llvm_mingw_wrapper(clang_path: &Path) -> bool {
4692 if let Some(filename) = clang_path
4693 .file_name()
4694 .and_then(|file_name| file_name.to_str())
4695 {
4696 filename.ends_with("-w64-mingw32-clang") || filename.ends_with("-w64-mingw32-clang++")
4697 } else {
4698 false
4699 }
4700}
4701
4702// FIXME: Use parsed target.
4703fn autodetect_android_compiler(raw_target: &str, gnu: &str, clang: &str) -> PathBuf {
4704 let new_clang_key = match raw_target {
4705 "aarch64-linux-android" => Some("aarch64"),
4706 "armv7-linux-androideabi" => Some("armv7a"),
4707 "i686-linux-android" => Some("i686"),
4708 "x86_64-linux-android" => Some("x86_64"),
4709 _ => None,
4710 };
4711
4712 let new_clang = new_clang_key
4713 .map(|key| {
4714 NEW_STANDALONE_ANDROID_COMPILERS
4715 .iter()
4716 .find(|x| x.starts_with(key))
4717 })
4718 .unwrap_or(None);
4719
4720 if let Some(new_clang) = new_clang {
4721 if Command::new(new_clang).output().is_ok() {
4722 return (*new_clang).into();
4723 }
4724 }
4725
4726 let target = raw_target
4727 .replace("armv7neon", "arm")
4728 .replace("armv7", "arm")
4729 .replace("thumbv7neon", "arm")
4730 .replace("thumbv7", "arm");
4731 let gnu_compiler = format!("{target}-{gnu}");
4732 let clang_compiler = format!("{target}-{clang}");
4733
4734 // On Windows, the Android clang compiler is provided as a `.cmd` file instead
4735 // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
4736 // `.cmd` is explicitly appended to the command name, so we do that here.
4737 let clang_compiler_cmd = format!("{target}-{clang}.cmd");
4738
4739 // Check if gnu compiler is present
4740 // if not, use clang
4741 if Command::new(&gnu_compiler).output().is_ok() {
4742 gnu_compiler
4743 } else if cfg!(windows) && Command::new(&clang_compiler_cmd).output().is_ok() {
4744 clang_compiler_cmd
4745 } else {
4746 clang_compiler
4747 }
4748 .into()
4749}
4750
4751// Rust and clang/cc don't agree on how to name the target.
4752fn map_darwin_target_from_rust_to_compiler_architecture<'a>(target: &TargetInfo<'a>) -> &'a str {
4753 match target.full_arch {
4754 "aarch64" => "arm64",
4755 "arm64_32" => "arm64_32",
4756 "arm64e" => "arm64e",
4757 "armv7k" => "armv7k",
4758 "armv7s" => "armv7s",
4759 "i386" => "i386",
4760 "i686" => "i386",
4761 "powerpc" => "ppc",
4762 "powerpc64" => "ppc64",
4763 "x86_64" => "x86_64",
4764 "x86_64h" => "x86_64h",
4765 arch => arch,
4766 }
4767}
4768
4769fn is_arm(target: &TargetInfo<'_>) -> bool {
4770 matches!(target.arch, "aarch64" | "arm64ec" | "arm")
4771}
4772
4773#[derive(Clone, Copy, PartialEq)]
4774enum AsmFileExt {
4775 /// `.asm` files. On MSVC targets, we assume these should be passed to MASM
4776 /// (`ml{,64}.exe`).
4777 DotAsm,
4778 /// `.s` or `.S` files, which do not have the special handling on MSVC targets.
4779 DotS,
4780}
4781
4782impl AsmFileExt {
4783 fn from_path(file: &Path) -> Option<Self> {
4784 if let Some(ext) = file.extension() {
4785 if let Some(ext) = ext.to_str() {
4786 let ext = ext.to_lowercase();
4787 match &*ext {
4788 "asm" => return Some(AsmFileExt::DotAsm),
4789 "s" => return Some(AsmFileExt::DotS),
4790 _ => return None,
4791 }
4792 }
4793 }
4794 None
4795 }
4796}
4797
4798fn check_exe(mut exe: PathBuf) -> Option<PathBuf> {
4799 let exe_ext = std::env::consts::EXE_EXTENSION;
4800 let check = exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists());
4801 check.then_some(exe)
4802}
4803
4804#[cfg(test)]
4805mod tests {
4806 use super::*;
4807
4808 #[test]
4809 fn test_android_clang_compiler_uses_target_arg_internally() {
4810 for version in 16..21 {
4811 assert!(android_clang_compiler_uses_target_arg_internally(
4812 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version))
4813 ));
4814 assert!(android_clang_compiler_uses_target_arg_internally(
4815 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version))
4816 ));
4817 }
4818 assert!(!android_clang_compiler_uses_target_arg_internally(
4819 &PathBuf::from("clang-i686-linux-android")
4820 ));
4821 assert!(!android_clang_compiler_uses_target_arg_internally(
4822 &PathBuf::from("clang")
4823 ));
4824 assert!(!android_clang_compiler_uses_target_arg_internally(
4825 &PathBuf::from("clang++")
4826 ));
4827 }
4828}