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:
extconf.rbexecution: Ruby'smkmf(make-makefile) library runs your extension'sextconf.rbscript.- Makefile generation: The
create_rust_makefilehelper fromrb-sysgenerates aMakefileconfigured to build your Rust code. cargo buildinvocation: TheMakefilecallscargo buildto compile your Rust crate into a dynamic shared library.- Library copying: The compiled library is moved into your gem's
libdirectory 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:
-
Enable Verbose Output:
bundle exec rake compile VERBOSE=1 -
Inspect the Makefile: Check
ext/my_gem/Makefileto see the exactcargocommands being run. -
Run Cargo Directly: Change into your extension directory and run
cargo buildmanually.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.