Skip to main content

The Build Process

This page explains the compilation steps for a Rust-based Ruby gem, aiding in debugging and optimization.

Compilation Steps

When you run bundle exec rake compile, the process involves:

  1. extconf.rb execution: Ruby's mkmf (make-makefile) library runs your extension's extconf.rb script.
  2. Makefile generation: The create_rust_makefile helper from rb-sys generates a Makefile configured to build your Rust code.
  3. cargo build invocation: The Makefile calls cargo build to compile your Rust crate into a dynamic shared library.
  4. Library copying: The compiled library is moved into your gem's lib directory for Ruby to load.

Build Configuration

Configure the build process in your extconf.rb file via the create_rust_makefile helper.

# ext/my_gem/extconf.rb
require "mkmf"
require "rb_sys/mkmf"

create_rust_makefile("my_gem") do |config|
config.profile = :release # Set the Cargo profile, e.g., :dev or :release
config.features = ["my-feature"] # Enable specific Cargo features
end

For a complete list of configuration options and environment variables, see the Gem Configuration reference.

Debugging a Failing Build

If rake compile fails, use these steps to diagnose the issue:

  1. Enable Verbose Output:

    bundle exec rake compile VERBOSE=1
  2. Inspect the Makefile: Check ext/my_gem/Makefile to see the exact cargo commands being run.

  3. Run Cargo Directly: Change into your extension directory and run cargo build manually.

    cd ext/my_gem
    cargo build --verbose

Optimizing Builds

For production gems, always compile with the release profile to enable optimizations. Control this with config.profile in extconf.rb or the RB_SYS_CARGO_PROFILE environment variable.

Tune release builds in your Cargo.toml:

[profile.release]
lto = true # Enable Link-Time Optimization
opt-level = 3 # Maximum optimization level
codegen-units = 1 # Slower to compile, but produces a smaller/faster binary

Cross-Compilation

rb-sys can compile your gem for different platforms (e.g., Linux, macOS, Windows) from a single machine using rb-sys-dock.

Enable cross-compilation in your Rakefile:

# Rakefile
RbSys::ExtensionTask.new("my_gem", GEMSPEC) do |ext|
ext.cross_compile = true
end

Build for a specific platform:

bundle exec rake native:my_gem:x86_64-linux

For a complete guide on setting up cross-compilation and CI/CD workflows, see the Deployment & Distribution guide.