### Initialize and Execute Install Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Creates an Install instance and executes the binary crate installation with Zig linker configuration. Useful for non-native targets. ```rust use cargo_zigbuild::Install; let mut install = Install::new(); install.execute()?; ``` -------------------------------- ### Install Binary with Zig Linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Install a binary (e.g., ripgrep) for a specified target using the Zig linker. ```bash cargo zigbuild install --target aarch64-unknown-linux-gnu ripgrep ``` -------------------------------- ### Example Usage of prepare_zig_linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/ZigWrapper.md Illustrates how to use the prepare_zig_linker function to obtain a ZigWrapper and print the paths to the generated wrapper scripts. ```rust use cargo_zigbuild::zig::prepare_zig_linker; use cargo_config2::Config; let config = Config::load()?; let wrapper = prepare_zig_linker("aarch64-unknown-linux-gnu", &config)?; println!("CC wrapper at: {}", wrapper.cc.display()); println!("CXX wrapper at: {}", wrapper.cxx.display()); println!("AR wrapper at: {}", wrapper.ar.display()); ``` -------------------------------- ### Execute Zig Cc Example Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Example of executing the `Zig::Cc` variant. This demonstrates how to pass arguments for compilation. ```rust use cargo_zigbuild::Zig; let zig = Zig::Cc { args: vec!["-target".to_string(), "x86_64-linux-gnu".to_string(), "test.c".to_string()], }; zig.execute()?; ``` -------------------------------- ### Install and Use cargo-zigbuild as a Binary Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/README.md Install the cargo-zigbuild binary and use it for cross-compilation. Ensure the target is added via rustup. ```bash cargo install cargo-zigbuild cargo zigbuild --target aarch64-unknown-linux-gnu --release ``` -------------------------------- ### Minimal Setup for Cross-Compilation Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/README.md Add the target architecture using rustup and then use cargo-zigbuild to compile for that target. ```bash rustup target add aarch64-unknown-linux-gnu cargo zigbuild --target aarch64-unknown-linux-gnu ``` -------------------------------- ### Initialize and Execute Run Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Creates a Run instance with a specified manifest path and executes the binary or example with Zig linker configuration. ```rust use cargo_zigbuild::Run; use std::path::PathBuf; let run = Run::new(Some(PathBuf::from("Cargo.toml"))); run.execute()?; ``` -------------------------------- ### Install Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md The `Install` struct wraps `cargo install` for installing binary crates with Zig linker support. It offers options to disable the Zig linker and enable Zig's `ar`. ```APIDOC ## Install ### Description Wraps `cargo install` to enable installing binary crates with Zig linker support. Allows configuration for disabling the Zig linker and enabling Zig's `ar`. ### Constructor `pub fn new() -> Self` Creates a new `Install` instance with default settings. This constructor does not take a manifest path as `cargo install` typically operates on crates rather than local packages. ### Public Fields - **cargo** (`cargo_options::Install`): Underlying Cargo install options. - **disable_zig_linker** (`bool`): If true, disables the Zig linker. - **enable_zig_ar** (`bool`): If true, enables Zig's `ar` utility. ### Methods #### execute `pub fn execute(&self) -> Result<()>` Executes `cargo install` with the configured Zig linker setup. This is particularly useful for installing Rust binaries for non-native targets. **Example:** ```rust use cargo_zigbuild::Install; let mut install = Install::new(); install.execute()?; ``` #### build_command `pub fn build_command(&self) -> Result` Generates a `std::process::Command` with the Zig linker environment configured. It uses `!self.debug` to determine the release mode. ``` -------------------------------- ### Windows GNU x86_64 Build Example Transformation (Zig 0.14+) Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/LinkerArgumentFiltering.md Illustrates the transformation of linker arguments for a Windows GNU x86_64 build, highlighting removed and added libraries based on Zig version. ```text Input: -target x86_64-windows-gnu -lwindows -lgcc_eh -lgcc -lmsvcrt Output (Zig 0.14+): -target x86_64-windows-gnu (removed) (kept or converted) (removed) (removed) -lcompiler_rt (added for Zig 0.16+) ``` -------------------------------- ### C Header File Example Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/docs/bindgen.md The header file declaring the C function. ```c // example.h int get_num(); ``` -------------------------------- ### Install cargo-zigbuild with Cargo Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/README.md Install the cargo-zigbuild tool using the cargo package manager. Ensure you use the --locked flag for reproducible builds. ```bash cargo install --locked cargo-zigbuild ``` -------------------------------- ### C Source File Example Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/docs/bindgen.md A simple C function to be compiled and linked. ```c // c-src/example.c int get_num() { return 42; } ``` -------------------------------- ### Glibc Version Targeting Examples Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/TargetSupport.md Examples of how to specify glibc versions for GNU targets. Appending the semantic version to the triple allows for precise compilation against a specific glibc release. ```bash x86_64-unknown-linux-gnu.2.17 aarch64-unknown-linux-gnu.2.28 x86_64-unknown-linux-gnu.2.32 ``` -------------------------------- ### macOS AArch64 Build Example Transformation (Zig 0.15) Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/LinkerArgumentFiltering.md Demonstrates the transformation of linker arguments for a macOS AArch64 build, showing removed flags for older Zig versions and modified undefined symbols. ```text Input: -target aarch64-apple-darwin -Wl,-exported_symbols_list,/path/to/list -lgcc_s -undefined dynamic_lookup Output (Zig 0.15): -target aarch64-apple-darwin (removed for Zig < 0.16) -lunwind -Wl,-undefined=dynamic_lookup ``` -------------------------------- ### Linux ARM64 Build Example Transformation Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/LinkerArgumentFiltering.md Shows the transformation of linker arguments for a Linux ARM64 build, including removal of certain libraries and modification of assembler flags. ```text Input: -target aarch64-linux-gnu -march=armv8+crypto -L /path/to/lib -lcompiler_builtins -lunwind -libc -lgcc_s Output: -target aarch64-linux-gnu -mcpu=generic+crypto -Xassembler -march=armv8+crypto -L /path/to/lib (libcompiler_builtins removed) -lunwind -libc -lunwind (replaced -lgcc_s) ``` -------------------------------- ### Install cargo-zigbuild with Pip Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/README.md Install cargo-zigbuild using pip, which also automatically installs the ziglang package. This is a convenient option for Python users. ```bash pip install cargo-zigbuild ``` -------------------------------- ### Execute Compiler with Arguments Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Example of using `execute_compiler` to run Zig compiler commands like `cc`. This shows how to pass compiler name and arguments. ```rust use cargo_zigbuild::Zig; let args = vec![ "-target".to_string(), "aarch64-linux-gnu".to_string(), "-c".to_string(), "main.c".to_string(), ]; Zig::Cc { args: args.clone() }.execute_compiler("cc", &args)?; ``` -------------------------------- ### Rust build.rs Example for CMake Integration Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CMakeIntegration.md Demonstrates how to use the `cmake` crate within a Rust build script to configure and build a C/C++ project. It shows how CMake automatically picks up the toolchain file via environment variables. ```rust use std::env; use std::path::Path; fn main() { let target = env::var("TARGET").unwrap(); if target.contains("linux") { // CMake will automatically use the toolchain file via // CMAKE_TOOLCHAIN_FILE environment variable let cmake = cmake::Config::new("src") .build(); // If explicitly needed: if let Ok(toolchain) = env::var("CMAKE_TOOLCHAIN_FILE_".to_owned() + &target.replace("-", "_")) { println!("cargo:rustc-link-search=native={}", cmake.join("install").join("lib").display()); } } } ``` -------------------------------- ### CMakeLists.txt Integration Example Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CMakeIntegration.md Shows how CMakeLists.txt can optionally check for and use the CMAKE_TOOLCHAIN_FILE environment variable, which is automatically set by cargo-zigbuild during the build process. ```cmake # If explicit toolchain inclusion is desired: if(DEFINED CMAKE_TOOLCHAIN_FILE) message(STATUS "Using CMake toolchain: ${CMAKE_TOOLCHAIN_FILE}") endif() ``` -------------------------------- ### Interacting with Zig Commands Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/ModuleStructure.md Illustrates how to import and use the Zig struct to interact with Zig commands, such as getting the Zig version or library directory. ```rust use cargo_zigbuild::Zig; let zig_version = Zig::zig_version()?; let zig_lib = Zig::lib_dir()?; ``` -------------------------------- ### Adding macOS Universal2 Target Architectures Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/README.md Before building a universal2 binary for macOS, add the necessary target architectures to your Rust installation using rustup. ```bash rustup target add x86_64-apple-darwin rustup target add aarch64-apple-darwin ``` -------------------------------- ### Catching Linker Response File Errors Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/errors.md This example shows how to catch specific errors related to linker response files, which can occur on Windows MSVC targets or due to decoding issues. It differentiates between response file errors and other general errors. ```rust match build.execute() { Ok(_) => println!("Build succeeded"), Err(e) if e.to_string().contains("response file") => { eprintln!("Linker response file error: {}", e); } Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Cargo Build Script Example (Bash) Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CMakeIntegration.md Illustrates how to invoke CMake from a cargo build script. When using cargo-zigbuild, necessary environment variables like CMAKE_TOOLCHAIN_FILE are automatically set, so no explicit passing is required. ```bash # When building with cargo zigbuild, environment variables are set # No explicit -DCMAKE_TOOLCHAIN_FILE needed in build script cmake ${CMAKE_OPTS} ``` -------------------------------- ### Rebuild cargo-zigbuild with Universal2 Feature Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Enables the 'universal2' feature when installing cargo-zigbuild to support universal2 binary creation. This is necessary if you encounter errors related to the 'universal2-apple-darwin' target. ```bash cargo install cargo-zigbuild --features universal2 ``` -------------------------------- ### Initialize and Execute Doc Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Creates a Doc instance with a specified manifest path and executes the documentation generation with Zig linker support. ```rust use cargo_zigbuild::Doc; use std::path::PathBuf; let doc = Doc::new(Some(PathBuf::from("Cargo.toml"))); doc.execute()?; ``` -------------------------------- ### Build::new Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Build.md Creates a new Build instance with an optional manifest path. ```APIDOC ## Build::new ### Description Creates a new `Build` instance with an optional manifest path pointing to a `Cargo.toml` file. ### Method Signature ```rust pub fn new(manifest_path: Option) -> Self ``` ### Parameters #### Path Parameters - **manifest_path** (`Option`) - Optional - Path to the Cargo.toml manifest file ### Returns A `Build` instance with the specified manifest path. ### Example ```rust use cargo_zigbuild::Build; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); ``` ``` -------------------------------- ### Test Running Universal2 Binary Natively and Emulated Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Demonstrates how to run a universal2 binary on Apple Silicon (native) and Intel Macs via Rosetta 2 (emulated). It also shows how to verify the actual architecture that executed the binary. ```bash # Run on Apple Silicon (native) ./target/universal2-apple-darwin/release/myapp # Run on Intel via Rosetta 2 (emulated) arch -x86_64 ./target/universal2-apple-darwin/release/myapp # Verify which architecture actually ran sysctl hw.machine ``` -------------------------------- ### Initialize and Execute Clippy Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Creates a Clippy instance with a specified manifest path and executes the linting process with Zig linker support. ```rust use cargo_zigbuild::Clippy; use std::path::PathBuf; let clippy = Clippy::new(Some(PathBuf::from("Cargo.toml"))); clippy.execute()?; ``` -------------------------------- ### Build Rust Project Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/CLAUDE.md Standard command to build a Rust project. ```bash cargo build ``` -------------------------------- ### Using cargo-zigbuild as a Library Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/ModuleStructure.md Demonstrates how to import and use core components like Build, Zig, Check, and Run when using cargo-zigbuild as a library. ```rust use cargo_zigbuild::{Build, Zig, Check, Run}; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); build.execute()?; ``` -------------------------------- ### Run Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md The `Run` struct wraps `cargo run` for executing binary or example crates with Zig linker support. It provides options to disable the Zig linker and enable Zig's `ar`. ```APIDOC ## Run ### Description Wraps `cargo run` to enable executing binary or example crates with Zig linker support. Allows configuration for disabling the Zig linker and enabling Zig's `ar`. ### Constructor `pub fn new(manifest_path: Option) -> Self` Creates a new `Run` instance. Accepts an optional `manifest_path`. ### Public Fields - **cargo** (`cargo_options::Run`): Underlying Cargo run options. - **disable_zig_linker** (`bool`): If true, disables the Zig linker. - **enable_zig_ar** (`bool`): If true, enables Zig's `ar` utility. ### Methods #### execute `pub fn execute(&self) -> Result<()>` Executes `cargo run` with the configured Zig linker setup. **Example:** ```rust use cargo_zigbuild::Run; use std::path::PathBuf; let run = Run::new(Some(PathBuf::from("Cargo.toml"))); run.execute()?; ``` #### build_command `pub fn build_command(&self) -> Result` Generates a `std::process::Command` with the Zig linker environment configured. ``` -------------------------------- ### Build with specific features Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Builds the project in release mode for the x86_64-unknown-linux-gnu target, activating specified features. ```bash cargo zigbuild --release --target x86_64-unknown-linux-gnu --features "feature1,feature2" ``` -------------------------------- ### Setting CMAKE_TOOLCHAIN_FILE for CMake Configuration Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CMakeIntegration.md When CMake fails to find headers, ensure the CMAKE_TOOLCHAIN_FILE environment variable is correctly set. This example shows how to export the path to the generated toolchain file before running a cargo zigbuild command. ```bash export CMAKE_TOOLCHAIN_FILE=/path/to/generated/toolchain.cmake cargo zigbuild --target aarch64-apple-darwin ``` -------------------------------- ### Applying Zig Wrappers in Command Environment Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/ZigWrapper.md Shows how to apply Zig wrapper paths to a command's environment variables, including platform-specific linker settings. ```rust let zig_wrapper = prepare_zig_linker(raw_target, &cargo_config)?; // For a target like "aarch64-unknown-linux-gnu", env_target becomes "aarch64_unknown_linux_gnu" let env_target = parsed_target.replace('-', "_"); // Set up environment for Cargo to use the wrappers Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &zig_wrapper.cc); Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &zig_wrapper.cxx); Self::add_env_if_missing(cmd, format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()), &zig_wrapper.cc); ``` -------------------------------- ### Transform -e to -Wl,--entry= Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/LinkerArgumentFiltering.md Converts -e to -Wl,--entry= for Zig's linker entry point specification. ```text -emain → -Wl,--entry=main ``` -------------------------------- ### Build::execute Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Build.md Executes the `cargo build` command with Zig as the linker. ```APIDOC ## Build::execute ### Description Executes the `cargo build` command with Zig as the linker. Spawns a child process and waits for completion. ### Method Signature ```rust pub fn execute(&self) -> Result<()> ``` ### Returns `Result<()>` - Success or error information. ### Throws - **anyhow::Error**: Failed to spawn cargo build process - **anyhow::Error**: Cargo build process failed with non-zero exit code ### Special Behavior (universal2 target) When building for `universal2-apple-darwin` target and the feature is enabled, this method: 1. Builds both `x86_64-apple-darwin` and `aarch64-apple-darwin` targets 2. Captures build artifacts from both targets 3. Creates fat Mach-O binaries combining the two architectures 4. Writes the universal binaries to the target directory ### Example ```rust use cargo_zigbuild::Build; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); match build.execute() { Ok(_) => println!("Build successful"), Err(e) => eprintln!("Build failed: {}", e), } ``` ``` -------------------------------- ### Create New Build Instance Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Build.md Instantiate a `Build` struct, optionally specifying the path to the `Cargo.toml` manifest file. ```rust use cargo_zigbuild::Build; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); ``` -------------------------------- ### Build for macOS from Linux Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Add the macOS ARM64 target and set the SDKROOT environment variable to build for macOS from a Linux environment. ```bash rustup target add aarch64-apple-darwin export SDKROOT=/path/to/macos/sdk cargo zigbuild --release --target aarch64-apple-darwin ``` -------------------------------- ### Add Universal2 Targets and Build Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Before building, ensure both underlying architectures are added as Rust targets. Then, use `cargo zigbuild` with the `universal2-apple-darwin` target. ```bash # Add both underlying targets rustup target add x86_64-apple-darwin rustup target add aarch64-apple-darwin # Build universal2 cargo zigbuild --release --target universal2-apple-darwin ``` -------------------------------- ### Build Single Architecture with Cargo Zigbuild Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Use standard targets for architecture-specific builds when partial builds for universal2 are not possible. ```bash cargo zigbuild --release --target aarch64-apple-darwin ``` -------------------------------- ### Build::from Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Build.md Automatically converts from `cargo_options::Build` to `Build` with default Zig settings. ```APIDOC ## Build::from ### Description Automatically converts from `cargo_options::Build` to `Build` with default Zig settings. ### Type Conversion ```rust impl From for Build ``` ### Example ```rust let cargo_build = cargo_options::Build::default(); let zig_build: cargo_zigbuild::Build = cargo_build.into(); ``` ``` -------------------------------- ### Initialize Test Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Creates a Test instance with an optional manifest path for running tests with Zig linker support. ```rust use cargo_zigbuild::Test; use std::path::PathBuf; let test = Test::new(Some(PathBuf::from("Cargo.toml"))); ``` -------------------------------- ### Windows GNU -Wl,-Bdynamic to -Wl,-search_paths_first Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/LinkerArgumentFiltering.md Replaces -Wl,-Bdynamic with -Wl,-search_paths_first for *-windows-gnu targets with Zig >= 0.11. ```text -Wl,-Bdynamic | Zig >= 0.11 | → -Wl,-search_paths_first ``` -------------------------------- ### Execute Build Command and Handle Status Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/README.md This Rust code demonstrates how to execute a build command and handle its success or failure status. It uses the anyhow crate for error handling. ```rust let build = Build::new(None); let mut cmd = build.build_command()?; match cmd.status() { Ok(status) if status.success() => println!("Success"), Ok(status) => eprintln!("Exit code: {:?}", status.code()), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Build::build_command Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Build.md Generates a `std::process::Command` with Zig linker environment variables set up. ```APIDOC ## Build::build_command ### Description Generates a `std::process::Command` with Zig linker environment variables set up. Does not execute the command. ### Method Signature ```rust pub fn build_command(&self) -> Result ``` ### Returns `Result` - A configured Command object ready to execute. ### Behavior - When `universal2-apple-darwin` is the target (feature enabled), builds for both x86_64 and aarch64 separately - When `disable_zig_linker` is true, skips Zig linker setup - Otherwise, applies Zig command environment configuration via `Zig::apply_command_env` ### Example ```rust use cargo_zigbuild::Build; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); let cmd = build.build_command()?; let status = cmd.status()?; ``` ``` -------------------------------- ### Build for x86_64 macOS using Docker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/README.md Utilize the provided Docker image to build for x86_64 macOS. The image includes macOS SDK, cargo-zigbuild, and Rust. Mount the current directory to the container's working directory. ```bash docker run --rm -it -v $(pwd):/io -w /io ghcr.io/rust-cross/cargo-zigbuild \ cargo zigbuild --release --target x86_64-apple-darwin ``` -------------------------------- ### Build with Specific Glibc Version Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Build a release binary for a specific x86_64 Linux target, specifying a glibc version. ```bash cargo zigbuild --release --target x86_64-unknown-linux-gnu.2.20 ``` -------------------------------- ### Accessing Platform-Specific Resources Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/ModuleStructure.md Shows how to import and access platform-specific resources, such as ARM features for Linux, from the cargo-zigbuild library. ```rust use cargo_zigbuild::linux; let arm_features = linux::ARM_FEATURES_H; ``` -------------------------------- ### Basic Library Build Execution Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/errors.md Use this snippet to perform a standard build using cargo-zigbuild. It handles basic error reporting, including the error chain. ```rust use cargo_zigbuild::Build; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); match build.execute() { Ok(_) => println!("Build successful"), Err(e) => { eprintln!("Build failed: {}", e); // e.chain() shows the error chain for cause in std::error::Error::sources(&*e) { eprintln!(" caused by: {}", cause); } } } ``` -------------------------------- ### Zig::Lib Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Wraps `zig lib` for Windows library creation (replacement for MSVC's `lib.exe`). ```APIDOC ## Zig::Lib ### Description Wraps `zig lib` for Windows library creation (replacement for MSVC's `lib.exe`). ### Fields - **args** (`Vec`) - Arguments to pass to `zig lib` ``` -------------------------------- ### apply_command_env Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Sets up environment variables and configuration for a Cargo command to use Zig as the linker. This is the main integration point between Cargo and Zig. ```APIDOC ## apply_command_env ### Description Sets up environment variables and configuration for a Cargo command to use Zig as the linker. This is the main integration point between Cargo and Zig. ### Method `apply_command_env` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **manifest_path** (`Option<&Path>`) - Optional - Path to Cargo.toml (optional) - **release** (`bool`) - Required - Whether building in release mode - **cargo** (`&cargo_options::CommonOptions`) - Required - Cargo's common options including targets - **cmd** (`&mut Command`) - Required - Command to configure - **enable_zig_ar** (`bool`) - Required - Whether to set AR environment variable ### Returns `Result<()>` ### Configures: - `CC_{target}` environment variable with Zig C compiler wrapper - `CXX_{target}` environment variable with Zig C++ compiler wrapper - `CARGO_TARGET_{target}_LINKER` environment variable - `RANLIB_{target}` environment variable - `AR_{target}` environment variable (if `enable_zig_ar` is true) - `BINDGEN_EXTRA_CLANG_ARGS_{target}` with include paths and compiler flags - `CMAKE_TOOLCHAIN_FILE_{target}` pointing to generated CMake toolchain - `PKG_CONFIG_SYSROOT_DIR` for Apple targets (auto-detects SDK root) - `CARGO_UNSTABLE_TARGET_APPLIES_TO_HOST` for same-target-as-host builds ### Example: ```rust use cargo_zigbuild::Zig; use std::process::Command; let mut cmd = Command::new("cargo"); cmd.arg("build"); Zig::apply_command_env( Some(std::path::Path::new("Cargo.toml")), true, &cargo_options::CommonOptions::default(), &mut cmd, true, )?; ``` ``` -------------------------------- ### Verifying Minimum GLIBC Version Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/README.md Run this command with the path to your compiled executable or library to check its minimum required GLIBC version using the 'get-min-glibc' script. ```console $ get-min-glibc target/x86_64-unknown-linux-gnu/release/hello-world 2.28 ``` -------------------------------- ### Building macOS Universal2 Binaries Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/README.md Use cargo zigbuild with the special 'universal2-apple-darwin' target to create macOS universal2 binaries. This requires Rust 1.64.0 or later. ```bash cargo zigbuild --target universal2-apple-darwin ``` -------------------------------- ### Build Zig Executable Command Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Constructs a `std::process::Command` to invoke the Zig executable. It intelligently searches for either `python -m ziglang` or a standalone `zig` binary. ```rust pub fn command() -> Result ``` ```rust use cargo_zigbuild::Zig; let mut cmd = Zig::command()?; cmd.arg("version"); let status = cmd.status()?; ``` -------------------------------- ### Build for a Specific Glibc Version Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/README.md Use this command to build your project for a specific glibc version. Ensure the target triple is correctly specified. ```bash # Build for glibc 2.17 car go zigbuild --target x86_64-unknown-linux-gnu.2.17 ``` -------------------------------- ### Execute Cargo Build with Zig Linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Build.md Executes the `cargo build` command using the Zig linker. This method spawns a child process and waits for its completion. It handles special behavior for the `universal2-apple-darwin` target by building both x86_64 and aarch64 architectures and creating fat Mach-O binaries. ```rust use cargo_zigbuild::Build; use std::path::PathBuf; let build = Build::new(Some(PathBuf::from("Cargo.toml"))); match build.execute() { Ok(_) => println!("Build successful"), Err(e) => eprintln!("Build failed: {}", e), } ``` -------------------------------- ### command Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Static method that builds a `std::process::Command` configured to invoke the Zig executable. Searches for either `python -m ziglang` or the `zig` binary. ```APIDOC ## command ### Description Static method that builds a `std::process::Command` configured to invoke the Zig executable. Searches for either `python -m ziglang` or the `zig` binary. ### Method `command()` ### Parameters None ### Returns `Result` - Configured Command ready for use. ### Throws: - `anyhow::Error` - Failed to find Zig executable ### Example: ```rust use cargo_zigbuild::Zig; let mut cmd = Zig::command()?; cmd.arg("version"); let status = cmd.status()?; ``` ``` -------------------------------- ### lib_dir Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Static method that determines the Zig standard library directory. Calls `zig env` and parses the output. Results are cached. ```APIDOC ## lib_dir ### Description Static method that determines the Zig standard library directory. Calls `zig env` and parses the output. Results are cached. ### Method `lib_dir()` ### Parameters None ### Returns `Result` - Path to Zig's lib directory ### Example: ```rust use cargo_zigbuild::Zig; let lib_dir = Zig::lib_dir()?; println!("Zig lib dir: {}", lib_dir.display()); ``` ``` -------------------------------- ### Configure Cargo Command Environment for Zig Linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Sets up environment variables and configurations for a Cargo command to utilize Zig as the linker. This is the primary integration point for Cargo and Zig builds. ```rust pub(crate) fn apply_command_env( manifest_path: Option<&Path>, release: bool, cargo: &cargo_options::CommonOptions, cmd: &mut Command, enable_zig_ar: bool, ) -> Result<()> ``` ```rust use cargo_zigbuild::Zig; use std::process::Command; let mut cmd = Command::new("cargo"); cmd.arg("build"); Zig::apply_command_env( Some(std::path::Path::new("Cargo.toml")), true, &cargo_options::CommonOptions::default(), &mut cmd, true, )?; ``` -------------------------------- ### Create Universal2 Binary with fat-macho Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Combines x86_64 and aarch64 Mach-O slices into a single universal2 binary. Non-Mach-O files are silently skipped. Ensure artifacts are valid Mach-O executables or dylibs. ```rust for (x86_64_path, aarch64_path) in x86_64_artifacts.iter().zip(aarch64_artifacts.iter()) { let mut fat = fat_macho::FatWriter::new(); // Add x86_64 slice match fat.add(fs_err::read(&x86_64_path)?) { Err(fat_macho::Error::InvalidMachO(_)) => continue, // Not a Mach-O file Err(e) => return Err(e)?, Ok(()) => {} } // Add aarch64 slice match fat.add(fs_err::read(&aarch64_path)?) { Err(fat_macho::Error::InvalidMachO(_)) => continue, // Not a Mach-O file Err(e) => return Err(e)?, Ok(()) => {} } // Write fat binary let universal2_path = PathBuf::from( x86_64_path.to_string().replace("x86_64-apple-darwin", "universal2-apple-darwin") ); let universal2_dir = universal2_path.parent().unwrap(); fs_err::create_dir_all(universal2_dir)?; fat.write_to_file(universal2_path)?; } ``` -------------------------------- ### Build for glibc 2.17 Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Builds the project in release mode for a target with a specific glibc version (2.17). ```bash cargo zigbuild --release --target aarch64-unknown-linux-gnu.2.17 ``` -------------------------------- ### ARM Generic Filters Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/LinkerArgumentFiltering.md Removes -march=* and libcompiler_builtins*.rlib for ARM targets, as Zig defaults are correct and it provides its own builtins. ```text -march=* → Removed (Zig defaults for ARM are correct) ``` ```text libcompiler_builtins*.rlib → Removed (Zig provides its own) ``` -------------------------------- ### Rust Build Script with Bindgen and CC Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/docs/bindgen.md Configures the build process, compiles C code, and generates Rust bindings using bindgen. Re-runs the build script if C source or header files change. ```rust // build.rs use std::{env, path::PathBuf}; fn main() { let target = env::var("TARGET").unwrap(); // Re-run this build script if the C source or header changes println!("cargo:rerun-if-changed=c-src/example.c"); println!("cargo:rerun-if-changed=c-src/example.h"); cc::Build::new().file("c-src/example.c").compile("example"); let bindings = bindgen::builder() .header("c-src/example.h") .use_core() .clang_arg(format!("--target={target}")) .generate().unwrap(); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings.write_to_file(out_path.join("example.rs")).unwrap(); } ``` -------------------------------- ### Execute Cargo Test with Zig Linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Instantiates and executes the `Test` struct to run `cargo test` with Zig linker configuration. Requires a manifest path. ```rust use cargo_zigbuild::Test; use std::path::PathBuf; let test = Test::new(Some(PathBuf::from("Cargo.toml"))); test.execute()?; ``` -------------------------------- ### Cross-compile for ARM64 Linux Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Add the ARM64 Linux target and then build a release binary for it using cargo-zigbuild. ```bash rustup target add aarch64-unknown-linux-gnu cargo zigbuild --release --target aarch64-unknown-linux-gnu ``` -------------------------------- ### Verify Architecture of Universal2 Binary Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Uses the `lipo` command to inspect the architectures included in a universal2 binary. The output should confirm the presence of both x86_64 and aarch64 slices. ```bash # Verify universal2 binary contains both slices lipo -info target/universal2-apple-darwin/release/myapp # Output should be: # Architectures in the fat file: x86_64 aarch64 ``` -------------------------------- ### Use cargo-zigbuild as a Library Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/README.md Integrate cargo-zigbuild into your Rust project as a library to programmatically build Rust projects. Requires the `anyhow` crate for error handling. ```rust use cargo_zigbuild::Build; use std::path::PathBuf; fn main() -> anyhow::Result<()> { let build = Build::new(Some(PathBuf::from("Cargo.toml"))); build.execute()?; Ok(()) } ``` -------------------------------- ### Execute Cargo Rustc with Zig Linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CargoSubcommands.md Instantiates and executes the `Rustc` struct to run `cargo rustc` with Zig linker configuration. Requires a manifest path. ```rust use cargo_zigbuild::Rustc; use std::path::PathBuf; let rustc = Rustc::new(Some(PathBuf::from("Cargo.toml"))); rustc.execute()?; ``` -------------------------------- ### prepare_zig_linker Function Signature Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/ZigWrapper.md Shows the signature of the prepare_zig_linker function, which creates Zig wrapper scripts. ```rust pub fn prepare_zig_linker( target: &str, cargo_config: &cargo_config2::Config, ) -> Result ``` -------------------------------- ### execute_dlltool Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Executes `zig dlltool` with automatic filtering of unsupported options for older Zig versions (< 0.12). ```APIDOC ## execute_dlltool ### Description Executes `zig dlltool` with automatic filtering of unsupported options for older Zig versions (< 0.12). ### Method `execute_dlltool` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **cmd_args** (`&[String]`) - Required - Arguments to pass to dlltool ### Returns `Result<()>` ### Behavior: - For Zig < 0.12: Filters out `--no-leading-underscore`, `--temp-prefix` (and `-t` short form) - For Zig >= 0.12: Passes arguments through unchanged - Falls back to `execute_tool("dlltool", filtered_args)` ### Example: ```rust use cargo_zigbuild::Zig; let args = vec![ "def".to_string(), "-m".to_string(), "i386".to_string(), "library.def".to_string(), ]; Zig::Dlltool { args: args.clone() }.execute_dlltool(&args)?; ``` ``` -------------------------------- ### Find Zig Executable and Arguments Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Locates the Zig executable, prioritizing the Python `ziglang` package and then the native binary. Results are cached for efficiency. It also returns additional arguments needed for Python invocation. ```rust pub fn find_zig() -> Result<(PathBuf, Vec)> ``` ```rust use cargo_zigbuild::Zig; let (zig_path, args) = Zig::find_zig()?; println!("Zig at: {}", zig_path.display()); if !args.is_empty() { println!("Using Python: python -m ziglang"); } ``` -------------------------------- ### Execute Zig dlltool with Version Filtering Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Executes `zig dlltool` while automatically filtering out unsupported options for Zig versions older than 0.12. Falls back to a generic tool execution for older versions. ```rust pub fn execute_dlltool(&self, cmd_args: &[String]) -> Result<()> ``` ```rust use cargo_zigbuild::Zig; let args = vec![ "def".to_string(), "-m".to_string(), "i386".to_string(), "library.def".to_string(), ]; Zig::Dlltool { args: args.clone() }.execute_dlltool(&args)?; ``` -------------------------------- ### Zig::Ar Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Wraps the `zig ar` archiver tool for creating static libraries. ```APIDOC ## Zig::Ar ### Description Wraps the `zig ar` archiver tool for creating static libraries. ### Fields - **args** (`Vec`) - Arguments to pass to `zig ar` ``` -------------------------------- ### Execute Cargo Check with Zig Linker Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Check.md Runs the `cargo check` command with the configured Zig linker settings. This method spawns a child process and waits for its completion. It returns an error if the process fails to spawn or exits with a non-zero status. ```rust use cargo_zigbuild::Check; use std::path::PathBuf; let check = Check::new(Some(PathBuf::from("Cargo.toml"))); check.execute()?; ``` -------------------------------- ### Applying CMake Toolchain Environment for Cargo Build Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/CMakeIntegration.md This Rust code snippet demonstrates how to use the `Zig::apply_command_env` function to set up the necessary environment variables for a Cargo build command, including the CMake toolchain file. This is useful when integrating cargo-zigbuild as a library. ```rust use cargo_zigbuild::Zig; use std::path::Path; // Set up environment (which includes CMake toolchain) let mut cmd = std::process::Command::new("cargo"); cmd.arg("build"); Zig::apply_command_env( Some(Path::new("Cargo.toml")), true, &cargo_options::CommonOptions::default(), &mut cmd, true, )?; // CMake_TOOLCHAIN_FILE_* variables are now set on cmd let status = cmd.status()?; ``` -------------------------------- ### Check::new Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Check.md Creates a new `Check` instance. This constructor allows specifying an optional path to the Cargo.toml manifest file. ```APIDOC ## Check::new ### Description Creates a new `Check` instance with an optional manifest path. ### Method `pub fn new(manifest_path: Option) -> Self` ### Parameters #### Path Parameters - **manifest_path** (`Option`) - Optional - Path to the Cargo.toml manifest file ### Example ```rust use cargo_zigbuild::Check; use std::path::PathBuf; let check = Check::new(Some(PathBuf::from("Cargo.toml"))); ``` ``` -------------------------------- ### Run Integration Tests Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/CLAUDE.md Command to execute integration tests for a Rust project using cargo-zigbuild. Requires specifying the manifest path and target. ```bash cargo run zigbuild --manifest-path tests//Cargo.toml --target ``` -------------------------------- ### Build with Universal2 Target and All Features Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Universal2Support.md Ensures all features are enabled for both targets when building with cargo-zigbuild to avoid artifact count mismatches. This command is useful when conditional compilation or feature flags differ between targets. ```bash cargo zigbuild --release --target universal2-apple-darwin --all-features ``` -------------------------------- ### Check::build_command Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Check.md Generates a `std::process::Command` object with the Zig linker environment variables pre-configured. This method does not execute the command but prepares it for execution. ```APIDOC ## Check::build_command ### Description Generates a `std::process::Command` with Zig linker environment variables configured. Does not execute the command. ### Method `pub fn build_command(&self) -> Result` ### Returns `Result` - A configured Command object ready to execute. ### Behavior - When `disable_zig_linker` is true, skips Zig linker setup. - Otherwise, applies Zig command environment via `Zig::apply_command_env`. - Uses the `release` and `target` fields from the underlying Cargo options. ### Example ```rust use cargo_zigbuild::Check; use std::path::PathBuf; let check = Check::new(Some(PathBuf::from("Cargo.toml"))); let cmd = check.build_command()?; let status = cmd.status()?; ``` ``` -------------------------------- ### Format Rust Project Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/CLAUDE.md Command to format a Rust project using cargo fmt. Applies formatting to all files. ```bash cargo fmt --all ``` -------------------------------- ### Zig::Dlltool Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/Zig.md Wraps `zig dlltool` for Windows DLL import library creation. Automatically filters unsupported options for older Zig versions. ```APIDOC ## Zig::Dlltool ### Description Wraps `zig dlltool` for Windows DLL import library creation. Automatically filters unsupported options for older Zig versions. ### Fields - **args** (`Vec`) - Arguments to pass to `zig dlltool` ``` -------------------------------- ### Build for aarch64 Linux Source: https://github.com/rust-cross/cargo-zigbuild/blob/main/_autodocs/configuration.md Builds the project in release mode for the aarch64-unknown-linux-gnu target. ```bash cargo zigbuild --release --target aarch64-unknown-linux-gnu ```