-
Notifications
You must be signed in to change notification settings - Fork 458
/
lib.rs
4175 lines (3838 loc) · 160 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A library for [Cargo build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html)
//! to compile a set of C/C++/assembly/CUDA files into a static archive for Cargo
//! to link into the crate being built. This crate does not compile code itself;
//! it calls out to the default compiler for the platform. This crate will
//! automatically detect situations such as cross compilation and
//! [various environment variables](#external-configuration-via-environment-variables) and will build code appropriately.
//!
//! # Example
//!
//! First, you'll want to both add a build script for your crate (`build.rs`) and
//! also add this crate to your `Cargo.toml` via:
//!
//! ```toml
//! [build-dependencies]
//! cc = "1.0"
//! ```
//!
//! Next up, you'll want to write a build script like so:
//!
//! ```rust,no_run
//! // build.rs
//! cc::Build::new()
//! .file("foo.c")
//! .file("bar.c")
//! .compile("foo");
//! ```
//!
//! And that's it! Running `cargo build` should take care of the rest and your Rust
//! application will now have the C files `foo.c` and `bar.c` compiled into a file
//! named `libfoo.a`. If the C files contain
//!
//! ```c
//! void foo_function(void) { ... }
//! ```
//!
//! and
//!
//! ```c
//! int32_t bar_function(int32_t x) { ... }
//! ```
//!
//! you can call them from Rust by declaring them in
//! your Rust code like so:
//!
//! ```rust,no_run
//! extern "C" {
//! fn foo_function();
//! fn bar_function(x: i32) -> i32;
//! }
//!
//! pub fn call() {
//! unsafe {
//! foo_function();
//! bar_function(42);
//! }
//! }
//!
//! fn main() {
//! call();
//! }
//! ```
//!
//! See [the Rustonomicon](https://doc.rust-lang.org/nomicon/ffi.html) for more details.
//!
//! # External configuration via environment variables
//!
//! To control the programs and flags used for building, the builder can set a
//! number of different environment variables.
//!
//! * `CFLAGS` - a series of space separated flags passed to compilers. Note that
//! individual flags cannot currently contain spaces, so doing
//! something like: `-L=foo\ bar` is not possible.
//! * `CC` - the actual C compiler used. Note that this is used as an exact
//! executable name, so (for example) no extra flags can be passed inside
//! this variable, and the builder must ensure that there aren't any
//! trailing spaces. This compiler must understand the `-c` flag. For
//! certain `TARGET`s, it also is assumed to know about other flags (most
//! common is `-fPIC`).
//! * `AR` - the `ar` (archiver) executable to use to build the static library.
//! * `CRATE_CC_NO_DEFAULTS` - the default compiler flags may cause conflicts in
//! some cross compiling scenarios. Setting this variable
//! will disable the generation of default compiler
//! flags.
//! * `CC_ENABLE_DEBUG_OUTPUT` - if set, compiler command invocations and exit codes will
//! be logged to stdout. This is useful for debugging build script issues, but can be
//! overly verbose for normal use.
//! * `CC_SHELL_ESCAPED_FLAGS` - if set, `*FLAGS` will be parsed as if they were shell
//! arguments (similar to `make` and `cmake`) rather than splitting them on each space.
//! For example, with `CFLAGS='a "b c"'`, the compiler will be invoked with 2 arguments -
//! `a` and `b c` - rather than 3: `a`, `"b` and `c"`.
//! * `CXX...` - see [C++ Support](#c-support).
//! * `CC_FORCE_DISABLE` - If set, `cc` will never run any [`Command`]s, and methods that
//! would return an [`Error`]. This is intended for use by third-party build systems
//! which want to be absolutely sure that they are in control of building all
//! dependencies. Note that operations that return [`Tool`]s such as
//! [`Build::get_compiler`] may produce less accurate results as in some cases `cc` runs
//! commands in order to locate compilers. Additionally, this does nothing to prevent
//! users from running [`Tool::to_command`] and executing the [`Command`] themselves.//!
//!
//! Furthermore, projects using this crate may specify custom environment variables
//! to be inspected, for example via the `Build::try_flags_from_environment`
//! function. Consult the project’s own documentation or its use of the `cc` crate
//! for any additional variables it may use.
//!
//! Each of these variables can also be supplied with certain prefixes and suffixes,
//! in the following prioritized order:
//!
//! 1. `<var>_<target>` - for example, `CC_x86_64-unknown-linux-gnu`
//! 2. `<var>_<target_with_underscores>` - for example, `CC_x86_64_unknown_linux_gnu`
//! 3. `<build-kind>_<var>` - for example, `HOST_CC` or `TARGET_CFLAGS`
//! 4. `<var>` - a plain `CC`, `AR` as above.
//!
//! If none of these variables exist, cc-rs uses built-in defaults.
//!
//! In addition to the above optional environment variables, `cc-rs` has some
//! functions with hard requirements on some variables supplied by [cargo's
//! build-script driver][cargo] that it has the `TARGET`, `OUT_DIR`, `OPT_LEVEL`,
//! and `HOST` variables.
//!
//! [cargo]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#inputs-to-the-build-script
//!
//! # Optional features
//!
//! ## Parallel
//!
//! Currently cc-rs supports parallel compilation (think `make -jN`) but this
//! feature is turned off by default. To enable cc-rs to compile C/C++ in parallel,
//! you can change your dependency to:
//!
//! ```toml
//! [build-dependencies]
//! cc = { version = "1.0", features = ["parallel"] }
//! ```
//!
//! By default cc-rs will limit parallelism to `$NUM_JOBS`, or if not present it
//! will limit it to the number of cpus on the machine. If you are using cargo,
//! use `-jN` option of `build`, `test` and `run` commands as `$NUM_JOBS`
//! is supplied by cargo.
//!
//! # Compile-time Requirements
//!
//! To work properly this crate needs access to a C compiler when the build script
//! is being run. This crate does not ship a C compiler with it. The compiler
//! required varies per platform, but there are three broad categories:
//!
//! * Unix platforms require `cc` to be the C compiler. This can be found by
//! installing cc/clang on Linux distributions and Xcode on macOS, for example.
//! * Windows platforms targeting MSVC (e.g. your target triple ends in `-msvc`)
//! require Visual Studio to be installed. `cc-rs` attempts to locate it, and
//! if it fails, `cl.exe` is expected to be available in `PATH`. This can be
//! set up by running the appropriate developer tools shell.
//! * Windows platforms targeting MinGW (e.g. your target triple ends in `-gnu`)
//! require `cc` to be available in `PATH`. We recommend the
//! [MinGW-w64](https://www.mingw-w64.org/) distribution.
//! You may also acquire it via
//! [MSYS2](https://www.msys2.org/), as explained [here][msys2-help]. Make sure
//! to install the appropriate architecture corresponding to your installation of
//! rustc. GCC from older [MinGW](http://www.mingw.org/) project is compatible
//! only with 32-bit rust compiler.
//!
//! [msys2-help]: https://github.com/rust-lang/rust/blob/master/INSTALL.md#building-on-windows
//!
//! # C++ support
//!
//! `cc-rs` supports C++ libraries compilation by using the `cpp` method on
//! `Build`:
//!
//! ```rust,no_run
//! cc::Build::new()
//! .cpp(true) // Switch to C++ library compilation.
//! .file("foo.cpp")
//! .compile("foo");
//! ```
//!
//! For C++ libraries, the `CXX` and `CXXFLAGS` environment variables are used instead of `CC` and `CFLAGS`.
//!
//! 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:
//!
//! 1. by using the `cpp_link_stdlib` method on `Build`:
//! ```rust,no_run
//! cc::Build::new()
//! .cpp(true)
//! .file("foo.cpp")
//! .cpp_link_stdlib("stdc++") // use libstdc++
//! .compile("foo");
//! ```
//! 2. by setting the `CXXSTDLIB` environment variable.
//!
//! 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).
//!
//! Remember that C++ does name mangling so `extern "C"` might be required to enable Rust linker to find your functions.
//!
//! # CUDA C++ support
//!
//! `cc-rs` also supports compiling CUDA C++ libraries by using the `cuda` method
//! on `Build`:
//!
//! ```rust,no_run
//! cc::Build::new()
//! // Switch to CUDA C++ library compilation using NVCC.
//! .cuda(true)
//! .cudart("static")
//! // Generate code for Maxwell (GTX 970, 980, 980 Ti, Titan X).
//! .flag("-gencode").flag("arch=compute_52,code=sm_52")
//! // Generate code for Maxwell (Jetson TX1).
//! .flag("-gencode").flag("arch=compute_53,code=sm_53")
//! // Generate code for Pascal (GTX 1070, 1080, 1080 Ti, Titan Xp).
//! .flag("-gencode").flag("arch=compute_61,code=sm_61")
//! // Generate code for Pascal (Tesla P100).
//! .flag("-gencode").flag("arch=compute_60,code=sm_60")
//! // Generate code for Pascal (Jetson TX2).
//! .flag("-gencode").flag("arch=compute_62,code=sm_62")
//! // Generate code in parallel
//! .flag("-t0")
//! .file("bar.cu")
//! .compile("bar");
//! ```
#![doc(html_root_url = "https://docs.rs/cc/1.0")]
#![deny(warnings)]
#![deny(missing_docs)]
#![deny(clippy::disallowed_methods)]
#![warn(clippy::doc_markdown)]
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt::{self, Display};
use std::fs;
use std::io::{self, Write};
use std::path::{Component, Path, PathBuf};
#[cfg(feature = "parallel")]
use std::process::Child;
use std::process::Command;
use std::sync::{
atomic::{AtomicU8, Ordering::Relaxed},
Arc, RwLock,
};
use shlex::Shlex;
#[cfg(feature = "parallel")]
mod parallel;
mod target;
mod windows;
use self::target::TargetInfo;
// Regardless of whether this should be in this crate's public API,
// it has been since 2015, so don't break it.
pub use windows::find_tools as windows_registry;
mod command_helpers;
use command_helpers::*;
mod tool;
pub use tool::Tool;
use tool::ToolFamily;
mod tempfile;
mod utilities;
use utilities::*;
mod flags;
use flags::*;
#[derive(Debug, Eq, PartialEq, Hash)]
struct CompilerFlag {
compiler: Box<Path>,
flag: Box<OsStr>,
}
type Env = Option<Arc<OsStr>>;
#[derive(Debug, Default)]
struct BuildCache {
env_cache: RwLock<HashMap<Box<str>, Env>>,
apple_sdk_root_cache: RwLock<HashMap<Box<str>, Arc<OsStr>>>,
apple_versions_cache: RwLock<HashMap<Box<str>, Arc<str>>>,
cached_compiler_family: RwLock<HashMap<Box<Path>, ToolFamily>>,
known_flag_support_status_cache: RwLock<HashMap<CompilerFlag, bool>>,
target_info_parser: target::TargetInfoParser,
}
/// A builder for compilation of a native library.
///
/// A `Build` is the main type of the `cc` crate and is used to control all the
/// various configuration options and such of a compile. You'll find more
/// documentation on each method itself.
#[derive(Clone, Debug)]
pub struct Build {
include_directories: Vec<Arc<Path>>,
definitions: Vec<(Arc<str>, Option<Arc<str>>)>,
objects: Vec<Arc<Path>>,
flags: Vec<Arc<OsStr>>,
flags_supported: Vec<Arc<OsStr>>,
ar_flags: Vec<Arc<OsStr>>,
asm_flags: Vec<Arc<OsStr>>,
no_default_flags: bool,
files: Vec<Arc<Path>>,
cpp: bool,
cpp_link_stdlib: Option<Option<Arc<str>>>,
cpp_set_stdlib: Option<Arc<str>>,
cuda: bool,
cudart: Option<Arc<str>>,
ccbin: bool,
std: Option<Arc<str>>,
target: Option<Arc<str>>,
/// The host compiler.
///
/// Try to not access this directly, and instead prefer `cfg!(...)`.
host: Option<Arc<str>>,
out_dir: Option<Arc<Path>>,
opt_level: Option<Arc<str>>,
debug: Option<bool>,
force_frame_pointer: Option<bool>,
env: Vec<(Arc<OsStr>, Arc<OsStr>)>,
compiler: Option<Arc<Path>>,
archiver: Option<Arc<Path>>,
ranlib: Option<Arc<Path>>,
cargo_output: CargoOutput,
link_lib_modifiers: Vec<Arc<OsStr>>,
pic: Option<bool>,
use_plt: Option<bool>,
static_crt: Option<bool>,
shared_flag: Option<bool>,
static_flag: Option<bool>,
warnings_into_errors: bool,
warnings: Option<bool>,
extra_warnings: Option<bool>,
emit_rerun_if_env_changed: bool,
shell_escaped_flags: Option<bool>,
build_cache: Arc<BuildCache>,
inherit_rustflags: bool,
}
/// Represents the types of errors that may occur while using cc-rs.
#[derive(Clone, Debug)]
enum ErrorKind {
/// Error occurred while performing I/O.
IOError,
/// Environment variable not found, with the var in question as extra info.
EnvVarNotFound,
/// Error occurred while using external tools (ie: invocation of compiler).
ToolExecError,
/// Error occurred due to missing external tools.
ToolNotFound,
/// One of the function arguments failed validation.
InvalidArgument,
/// No known macro is defined for the compiler when discovering tool family.
ToolFamilyMacroNotFound,
/// Invalid target.
InvalidTarget,
/// Invalid rustc flag.
InvalidFlag,
#[cfg(feature = "parallel")]
/// jobserver helpthread failure
JobserverHelpThreadError,
/// `cc` has been disabled by an environment variable.
Disabled,
}
/// Represents an internal error that occurred, with an explanation.
#[derive(Clone, Debug)]
pub struct Error {
/// Describes the kind of error that occurred.
kind: ErrorKind,
/// More explanation of error that occurred.
message: Cow<'static, str>,
}
impl Error {
fn new(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Error {
Error {
kind,
message: message.into(),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::new(ErrorKind::IOError, format!("{}", e))
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {}", self.kind, self.message)
}
}
impl std::error::Error for Error {}
/// Represents an object.
///
/// This is a source file -> object file pair.
#[derive(Clone, Debug)]
struct Object {
src: PathBuf,
dst: PathBuf,
}
impl Object {
/// Create a new source file -> object file pair.
fn new(src: PathBuf, dst: PathBuf) -> Object {
Object { src, dst }
}
}
impl Build {
/// Construct a new instance of a blank set of configuration.
///
/// This builder is finished with the [`compile`] function.
///
/// [`compile`]: struct.Build.html#method.compile
pub fn new() -> Build {
Build {
include_directories: Vec::new(),
definitions: Vec::new(),
objects: Vec::new(),
flags: Vec::new(),
flags_supported: Vec::new(),
ar_flags: Vec::new(),
asm_flags: Vec::new(),
no_default_flags: false,
files: Vec::new(),
shared_flag: None,
static_flag: None,
cpp: false,
cpp_link_stdlib: None,
cpp_set_stdlib: None,
cuda: false,
cudart: None,
ccbin: true,
std: None,
target: None,
host: None,
out_dir: None,
opt_level: None,
debug: None,
force_frame_pointer: None,
env: Vec::new(),
compiler: None,
archiver: None,
ranlib: None,
cargo_output: CargoOutput::new(),
link_lib_modifiers: Vec::new(),
pic: None,
use_plt: None,
static_crt: None,
warnings: None,
extra_warnings: None,
warnings_into_errors: false,
emit_rerun_if_env_changed: true,
shell_escaped_flags: None,
build_cache: Arc::default(),
inherit_rustflags: true,
}
}
/// Add a directory to the `-I` or include path for headers
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
///
/// let library_path = Path::new("/path/to/library");
///
/// cc::Build::new()
/// .file("src/foo.c")
/// .include(library_path)
/// .include("src")
/// .compile("foo");
/// ```
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build {
self.include_directories.push(dir.as_ref().into());
self
}
/// Add multiple directories to the `-I` include path.
///
/// # Example
///
/// ```no_run
/// # use std::path::Path;
/// # let condition = true;
/// #
/// let mut extra_dir = None;
/// if condition {
/// extra_dir = Some(Path::new("/path/to"));
/// }
///
/// cc::Build::new()
/// .file("src/foo.c")
/// .includes(extra_dir)
/// .compile("foo");
/// ```
pub fn includes<P>(&mut self, dirs: P) -> &mut Build
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
for dir in dirs {
self.include(dir);
}
self
}
/// Specify a `-D` variable with an optional value.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .define("FOO", "BAR")
/// .define("BAZ", None)
/// .compile("foo");
/// ```
pub fn define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build {
self.definitions
.push((var.into(), val.into().map(Into::into)));
self
}
/// Add an arbitrary object file to link in
pub fn object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build {
self.objects.push(obj.as_ref().into());
self
}
/// Add arbitrary object files to link in
pub fn objects<P>(&mut self, objs: P) -> &mut Build
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
for obj in objs {
self.object(obj);
}
self
}
/// Add an arbitrary flag to the invocation of the compiler
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .flag("-ffunction-sections")
/// .compile("foo");
/// ```
pub fn flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
self.flags.push(flag.as_ref().into());
self
}
/// Removes a compiler flag that was added by [`Build::flag`].
///
/// Will not remove flags added by other means (default flags,
/// flags from env, and so on).
///
/// # Example
/// ```
/// cc::Build::new()
/// .file("src/foo.c")
/// .flag("unwanted_flag")
/// .remove_flag("unwanted_flag");
/// ```
pub fn remove_flag(&mut self, flag: &str) -> &mut Build {
self.flags.retain(|other_flag| &**other_flag != flag);
self
}
/// Add a flag to the invocation of the ar
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .file("src/bar.c")
/// .ar_flag("/NODEFAULTLIB:libc.dll")
/// .compile("foo");
/// ```
pub fn ar_flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
self.ar_flags.push(flag.as_ref().into());
self
}
/// Add a flag that will only be used with assembly files.
///
/// The flag will be applied to input files with either a `.s` or
/// `.asm` extension (case insensitive).
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .asm_flag("-Wa,-defsym,abc=1")
/// .file("src/foo.S") // The asm flag will be applied here
/// .file("src/bar.c") // The asm flag will not be applied here
/// .compile("foo");
/// ```
pub fn asm_flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
self.asm_flags.push(flag.as_ref().into());
self
}
fn ensure_check_file(&self) -> Result<PathBuf, Error> {
let out_dir = self.get_out_dir()?;
let src = if self.cuda {
assert!(self.cpp);
out_dir.join("flag_check.cu")
} else if self.cpp {
out_dir.join("flag_check.cpp")
} else {
out_dir.join("flag_check.c")
};
if !src.exists() {
let mut f = fs::File::create(&src)?;
write!(f, "int main(void) {{ return 0; }}")?;
}
Ok(src)
}
/// Run the compiler to test if it accepts the given flag.
///
/// For a convenience method for setting flags conditionally,
/// see `flag_if_supported()`.
///
/// It may return error if it's unable to run the compiler with a test file
/// (e.g. the compiler is missing or a write to the `out_dir` failed).
///
/// Note: Once computed, the result of this call is stored in the
/// `known_flag_support` field. If `is_flag_supported(flag)`
/// is called again, the result will be read from the hash table.
pub fn is_flag_supported(&self, flag: impl AsRef<OsStr>) -> Result<bool, Error> {
self.is_flag_supported_inner(
flag.as_ref(),
self.get_base_compiler()?.path(),
&self.get_target()?,
)
}
fn is_flag_supported_inner(
&self,
flag: &OsStr,
compiler_path: &Path,
target: &TargetInfo<'_>,
) -> Result<bool, Error> {
let compiler_flag = CompilerFlag {
compiler: compiler_path.into(),
flag: flag.into(),
};
if let Some(is_supported) = self
.build_cache
.known_flag_support_status_cache
.read()
.unwrap()
.get(&compiler_flag)
.cloned()
{
return Ok(is_supported);
}
let out_dir = self.get_out_dir()?;
let src = self.ensure_check_file()?;
let obj = out_dir.join("flag_check");
let mut compiler = {
let mut cfg = Build::new();
cfg.flag(flag)
.compiler(compiler_path)
.cargo_metadata(self.cargo_output.metadata)
.opt_level(0)
.debug(false)
.cpp(self.cpp)
.cuda(self.cuda)
.inherit_rustflags(false)
.emit_rerun_if_env_changed(self.emit_rerun_if_env_changed);
if let Some(target) = &self.target {
cfg.target(target);
}
if let Some(host) = &self.host {
cfg.host(host);
}
cfg.try_get_compiler()?
};
// Clang uses stderr for verbose output, which yields a false positive
// result if the CFLAGS/CXXFLAGS include -v to aid in debugging.
if compiler.family.verbose_stderr() {
compiler.remove_arg("-v".into());
}
if compiler.is_like_clang() {
// Avoid reporting that the arg is unsupported just because the
// compiler complains that it wasn't used.
compiler.push_cc_arg("-Wno-unused-command-line-argument".into());
}
let mut cmd = compiler.to_command();
let is_arm = matches!(target.arch, "aarch64" | "arm");
let clang = compiler.is_like_clang();
let gnu = compiler.family == ToolFamily::Gnu;
command_add_output_file(
&mut cmd,
&obj,
CmdAddOutputFileArgs {
cuda: self.cuda,
is_assembler_msvc: false,
msvc: compiler.is_like_msvc(),
clang,
gnu,
is_asm: false,
is_arm,
},
);
// Checking for compiler flags does not require linking
cmd.arg("-c");
cmd.arg(&src);
let output = cmd.output()?;
let is_supported = output.status.success() && output.stderr.is_empty();
self.build_cache
.known_flag_support_status_cache
.write()
.unwrap()
.insert(compiler_flag, is_supported);
Ok(is_supported)
}
/// Add an arbitrary flag to the invocation of the compiler if it supports it
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .flag_if_supported("-Wlogical-op") // only supported by GCC
/// .flag_if_supported("-Wunreachable-code") // only supported by clang
/// .compile("foo");
/// ```
pub fn flag_if_supported(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
self.flags_supported.push(flag.as_ref().into());
self
}
/// Add flags from the specified environment variable.
///
/// Normally the `cc` crate will consult with the standard set of environment
/// variables (such as `CFLAGS` and `CXXFLAGS`) to construct the compiler invocation. Use of
/// this method provides additional levers for the end user to use when configuring the build
/// process.
///
/// Just like the standard variables, this method will search for an environment variable with
/// appropriate target prefixes, when appropriate.
///
/// # Examples
///
/// This method is particularly beneficial in introducing the ability to specify crate-specific
/// flags.
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .try_flags_from_environment(concat!(env!("CARGO_PKG_NAME"), "_CFLAGS"))
/// .expect("the environment variable must be specified and UTF-8")
/// .compile("foo");
/// ```
///
pub fn try_flags_from_environment(&mut self, environ_key: &str) -> Result<&mut Build, Error> {
let flags = self.envflags(environ_key)?;
self.flags.extend(
flags
.into_iter()
.map(|flag| Arc::from(OsString::from(flag).as_os_str())),
);
Ok(self)
}
/// Set the `-shared` flag.
///
/// When enabled, the compiler will produce a shared object which can
/// then be linked with other objects to form an executable.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .shared_flag(true)
/// .compile("libfoo.so");
/// ```
pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build {
self.shared_flag = Some(shared_flag);
self
}
/// Set the `-static` flag.
///
/// When enabled on systems that support dynamic linking, this prevents
/// linking with the shared libraries.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .shared_flag(true)
/// .static_flag(true)
/// .compile("foo");
/// ```
pub fn static_flag(&mut self, static_flag: bool) -> &mut Build {
self.static_flag = Some(static_flag);
self
}
/// Disables the generation of default compiler flags. The default compiler
/// flags may cause conflicts in some cross compiling scenarios.
///
/// Setting the `CRATE_CC_NO_DEFAULTS` environment variable has the same
/// effect as setting this to `true`. The presence of the environment
/// variable and the value of `no_default_flags` will be OR'd together.
pub fn no_default_flags(&mut self, no_default_flags: bool) -> &mut Build {
self.no_default_flags = no_default_flags;
self
}
/// Add a file which will be compiled
pub fn file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build {
self.files.push(p.as_ref().into());
self
}
/// Add files which will be compiled
pub fn files<P>(&mut self, p: P) -> &mut Build
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
for file in p.into_iter() {
self.file(file);
}
self
}
/// Get the files which will be compiled
pub fn get_files(&self) -> impl Iterator<Item = &Path> {
self.files.iter().map(AsRef::as_ref)
}
/// Set C++ support.
///
/// The other `cpp_*` options will only become active if this is set to
/// `true`.
///
/// The name of the C++ standard library to link is decided by:
/// 1. If [`cpp_link_stdlib`](Build::cpp_link_stdlib) is set, use its value.
/// 2. Else if the `CXXSTDLIB` environment variable is set, use its value.
/// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
/// `None` for MSVC and `stdc++` for anything else.
pub fn cpp(&mut self, cpp: bool) -> &mut Build {
self.cpp = cpp;
self
}
/// Set CUDA C++ support.
///
/// Enabling CUDA will invoke the CUDA compiler, NVCC. While NVCC accepts
/// the most common compiler flags, e.g. `-std=c++17`, some project-specific
/// flags might have to be prefixed with "-Xcompiler" flag, for example as
/// `.flag("-Xcompiler").flag("-fpermissive")`. See the documentation for
/// `nvcc`, the CUDA compiler driver, at <https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/>
/// for more information.
///
/// If enabled, this also implicitly enables C++ support.
pub fn cuda(&mut self, cuda: bool) -> &mut Build {
self.cuda = cuda;
if cuda {
self.cpp = true;
self.cudart = Some("static".into());
}
self
}
/// Link CUDA run-time.
///
/// This option mimics the `--cudart` NVCC command-line option. Just like
/// the original it accepts `{none|shared|static}`, with default being
/// `static`. The method has to be invoked after `.cuda(true)`, or not
/// at all, if the default is right for the project.
pub fn cudart(&mut self, cudart: &str) -> &mut Build {
if self.cuda {
self.cudart = Some(cudart.into());
}
self
}
/// Set CUDA host compiler.
///
/// By default, a `-ccbin` flag will be passed to NVCC to specify the
/// underlying host compiler. The value of `-ccbin` is the same as the
/// chosen C++ compiler. This is not always desired, because NVCC might
/// not support that compiler. In this case, you can remove the `-ccbin`
/// flag so that NVCC will choose the host compiler by itself.
pub fn ccbin(&mut self, ccbin: bool) -> &mut Build {
self.ccbin = ccbin;
self
}
/// Specify the C or C++ language standard version.
///
/// These values are common to modern versions of GCC, Clang and MSVC:
/// - `c11` for ISO/IEC 9899:2011
/// - `c17` for ISO/IEC 9899:2018
/// - `c++14` for ISO/IEC 14882:2014
/// - `c++17` for ISO/IEC 14882:2017
/// - `c++20` for ISO/IEC 14882:2020
///
/// Other values have less broad support, e.g. MSVC does not support `c++11`
/// (`c++14` is the minimum), `c89` (omit the flag instead) or `c99`.
///
/// For compiling C++ code, you should also set `.cpp(true)`.
///
/// The default is that no standard flag is passed to the compiler, so the
/// language version will be the compiler's default.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/modern.cpp")
/// .cpp(true)
/// .std("c++17")
/// .compile("modern");
/// ```
pub fn std(&mut self, std: &str) -> &mut Build {
self.std = Some(std.into());
self
}
/// Set warnings into errors flag.
///
/// Disabled by default.
///
/// Warning: turning warnings into errors only make sense
/// if you are a developer of the crate using cc-rs.
/// Some warnings only appear on some architecture or
/// specific version of the compiler. Any user of this crate,
/// or any other crate depending on it, could fail during
/// compile time.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .warnings_into_errors(true)
/// .compile("libfoo.a");
/// ```
pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build {
self.warnings_into_errors = warnings_into_errors;
self
}
/// Set warnings flags.
///
/// Adds some flags:
/// - "-Wall" for MSVC.
/// - "-Wall", "-Wextra" for GNU and Clang.
///
/// Enabled by default.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .warnings(false)
/// .compile("libfoo.a");
/// ```
pub fn warnings(&mut self, warnings: bool) -> &mut Build {
self.warnings = Some(warnings);
self.extra_warnings = Some(warnings);
self
}
/// Set extra warnings flags.
///