Building

Building if you're using cargo

The basics of building in a cargo environment are explained in the tutorial.

If your build depends on later editions of the C++ standard library, you will need to ensure that both libclang and the compiler are sent the appropriate flag, like this:

fn main() { let path = std::path::PathBuf::from("src"); // include path let mut b = autocxx_build::Builder::new("src/main.rs", &[&path]) .extra_clang_args(&["-std=c++17"]) .build() .unwrap(); b.flag_if_supported("-std=c++17") // use "-std:c++17" here if using msvc on windows .compile("autocxx-demo"); // arbitrary library name, pick anything println!("cargo:rerun-if-changed=src/main.rs"); // Add instructions to link to any C++ libraries you need. }

Building - if you're not using cargo

See the autocxx-gen crate. You'll need to:

  • Run the codegen phase. You'll need to use the autocxx-gen tool to process the .rs code into C++ header and implementation files. This will also generate .rs side bindings.
  • Educate the procedural macro about where to find the generated .rs bindings. Set the AUTOCXX_RS environment variable to a list of directories to search. If you use autocxx-build, this happens automatically. (You can alternatively specify AUTOCXX_RS_FILE to give a precise filename as opposed to a directory to search, though this isn't recommended unless your build system specifically requires it because it allows only a single include_cpp! block per .rs file.) See gen --help for details on the naming of the generated files.
included
Rust source with include_cpp!
Existing C++ headers
autocxx-gen or autocxx-build
Generated .rs file
Generated .cpp and .h files
Rust/Cargo build
C++ build
Linker
autocxx-macro

This interop inevitably involves lots of fiddly small functions. It's likely to perform far better if you can achieve cross-language link-time-optimization (LTO). This issue may give some useful hints - see also all the build-related help in the cxx manual which all applies here too.

C++ versions and other compiler command-line flags

The code generated by cxx and autocxx requires C++ 14, so it's not possible to use an earlier version of C++ than that.

To use a later version, you need to:

  • Build the generated code with a later C++ version, for example using the clang argument -std=c++17. If you're using autocxx's cargo support, then you would do this by calling methods on the returned cc::Build object, for instance flag_if_supported.
  • Also give similar directives to the C++ parsing which happens within autocxx (specifically, by autocxx's version of bindgen). To do that, use Builder::extra_clang_args.

The same applies with the command-line autocxx_gen support - you'll need to pass such extra compiler options to autocxx_gen and also use them when building the generated C++ code.