Portable mruby binaries with Cosmopolitan
Source: Dev.to
Background
One of the main attractions of mruby is its ability to create standalone executables. While this works well, a classic limitation is that most standalone binaries can only run on the same, or very similar, system they were built on. For example, an executable built on amd64 Linux will not run on a Silicon Mac:
$ ./hello
exec: Failed to execute process: './hello' the file could not be run by the operating system.
exec: Maybe the interpreter directive (#! line) is broken?
mruby does have some cross‑compilation capabilities, but they can feel intimidating and are often difficult to get working (e.g., Linux → macOS). This raises the question: Can we build truly portable mruby binaries without a macOS Docker image?
Cosmopolitan Libc
While browsing the mruby changelog, an entry caught my eye:
New Platform: Cosmopolitan Libc
Cosmopolitan Libc aims to make C a “build‑anywhere, run‑anywhere” language, similar to Java but without requiring an interpreter or virtual machine. It reconfigures GCC/Clang to emit a POSIX‑approved polyglot format that runs natively on:
- Linux
- macOS
- Windows
- FreeBSD, OpenBSD, NetBSD
- BIOS (AMD64 & ARM64)
Performance is close to native.
Building mruby with Cosmopolitan
Prerequisites
-
Download the Cosmopolitan toolkit:
wget https://cosmo.zip/pub/cosmocc/cosmocc.zip unzip cosmocc.zip -d ~/Downloads/cosmocc -
Ensure the toolkit is extracted to
~/Downloads/cosmocc(or adjust the path accordingly).
Step 1 – Build mruby
COSMO_ROOT=~/Downloads/cosmocc rake MRUBY_CONFIG=cosmopolitan
Note: At the time of writing, the
mirbtarget had to be removed from the configuration because it fails to compile with Cosmopolitan.
Step 2 – Generate bytecode
Use the Cosmopolitan‑specific mrbc binary:
./mruby/bin/mrbc.com -Bhello_world hello.rb
This produces a C array named hello_world containing the compiled Ruby bytecode.
Step 3 – Compile the final executable
~/Downloads/cosmocc/bin/cosmocc -std=c99 -Imruby/include main.c \
-o hello mruby/build/host/lib/libmruby.a -lm
main.cis a small C entry file that loads the generated bytecode.- The resulting
hellobinary is a Cosmopolitan executable.
Result
The produced hello binary runs on both Linux and macOS (including Apple Silicon) without modification. The binary is larger than a traditional mruby executable, which is the trade‑off for portability, but it simplifies distribution when targeting multiple platforms.