Skip to content

Commit

Permalink
Add method for specifying C/C++ standard version
Browse files Browse the repository at this point in the history
  • Loading branch information
hikari-no-yume committed Dec 5, 2022
1 parent 0e51f6d commit 7163670
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ pub struct Build {
cpp_set_stdlib: Option<String>,
cuda: bool,
cudart: Option<String>,
std: Option<String>,
target: Option<String>,
host: Option<String>,
out_dir: Option<PathBuf>,
Expand Down Expand Up @@ -311,6 +312,7 @@ impl Build {
cpp_set_stdlib: None,
cuda: false,
cudart: None,
std: None,
target: None,
host: None,
out_dir: None,
Expand Down Expand Up @@ -665,6 +667,36 @@ impl Build {
self
}

/// Specify the C or C++ language standard version.
///
/// Common values accepted by 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 like `c99`, `gnu89` and `c++11` have less broad support.
///
/// 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.to_string());
self
}

/// Set warnings into errors flag.
///
/// Disabled by default.
Expand Down Expand Up @@ -1500,6 +1532,14 @@ impl Build {
println!("Info: default compiler flags are disabled");
}

if let Some(ref std) = self.std {
let separator = match cmd.family {
ToolFamily::Msvc { .. } => ':',
ToolFamily::Gnu | ToolFamily::Clang => '=',
};
cmd.push_cc_arg(format!("-std{}{}", separator, std).into());
}

for arg in envflags {
cmd.push_cc_arg(arg.into());
}
Expand Down
16 changes: 16 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,14 @@ fn gnu_no_dash_dash() {
test.cmd(0).must_not_have("--");
}

#[test]
fn gnu_std_c() {
let test = Test::gnu();
test.gcc().file("foo.c").std("c11").compile("foo");

test.cmd(0).must_have("-std=c11");
}

#[test]
fn msvc_smoke() {
reset_env();
Expand Down Expand Up @@ -443,6 +451,14 @@ fn msvc_no_dash_dash() {
test.cmd(0).must_not_have("--");
}

#[test]
fn msvc_std_c() {
let test = Test::msvc();
test.gcc().file("foo.c").std("c11").compile("foo");

test.cmd(0).must_have("-std:c11");
}

// Disable this test with the parallel feature because the execution
// order is not deterministic.
#[cfg(not(feature = "parallel"))]
Expand Down

0 comments on commit 7163670

Please sign in to comment.