Mruby

Metadata
glitched logo of mruby

mruby is a ruby implementation that allows compiling ruby code, unfortunately there's not so much documentation around therefore this is a dump of the info I gather for my personal use.

Compile mruby with require support

Why ?

In order to compile a ruby library that uses the require syntax.

Compiling

  1. Clone mruby project git clone https://github.com/mruby/mruby.git
  2. Change build_config/default.rb to :
MRuby::Build.new do |conf|
  if ENV['OS'] != 'Windows_NT' then
    conf.cc.flags << %w|-fPIC| # needed for using bundled gems
  end
  conf.toolchain
  conf.gembox 'default'
  conf.enable_bintest
  conf.enable_test
  conf.gem :github => 'mattn/mruby-require'
end
  1. Compile using rake in the root folder
  2. The binaries are compiled into build/host/bin

Compile a simple ruby file with mruby

What is this document for ?

mruby is an emdedded version of ruby, here's how to compile a simple ruby file into C file. This memo is using mruby's official compiling guide.

Install mruby

Using rbenv :

  1. look which version of mruby is available to install : rbenv install -l
  2. at the time I'm writing this memo the version is mruby-2.1.2 : rbenv install mruby-2.1.2

Create project folder

mkdir my_project
cd my_project
rbenv local mruby-2.1.2

Create the needed files

You need the following files in the project folder:

  1. Your ruby file to compile, in this case called test.rb :
puts "this is a test"
  1. A file that will handle your c code here called test_stub.c :
#include <mruby.h>
#include <mruby/irep.h>
#include "test.c"

int
main(void)
{
  mrb_state *mrb = mrb_open();
  if (!mrb) { /* handle error */ }
  mrb_load_irep(mrb, test_symbol);
  mrb_close(mrb);
  return 0;
}

Compile your ruby file to C

Compiling to c file is straight forward : mrbc -Btest_symbol test.rb should produce a file named test.c

Compile your C file

using gcc you can compile you test.c like that :

gcc -std=c99 -I /Users/username/.rbenv/versions/mruby-2.1.2/include/ test_stub.c -o test_program /Users/username/.rbenv/versions/mruby-2.1.2/lib/libmruby.a -lm

Execute your newly compiled program

./test_program should print this is a test