Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active November 9, 2017 05:05
Show Gist options
  • Save havenwood/4955907 to your computer and use it in GitHub Desktop.
Save havenwood/4955907 to your computer and use it in GitHub Desktop.
Little script using mruby to compile to self-executable
#!/usr/bin/env ruby
class Compiler
def initialize
@mruby_dir = '/Users/shannonskipper/.rubies/mruby'
sanity_check_argv
@file = ARGV.first.sub /.rb$/, ''
end
def run
create_binary_c_code_array
wrap_binary_c_code_array
compile_and_link
end
private
def sanity_check_argv
if ARGV.empty?
abort 'Pass the .rb file do you want to compile as an arguement.'
end
unless ARGV.first =~ /.rb$/
abort 'The @file you are compiling must be a .rb file.'
end
end
def create_binary_c_code_array
`#{@mruby_dir}/bin/mrbc -B#{@file} #{@file}.rb`
end
def wrap_binary_c_code_array
File.open "./#{@file}.c", 'a' do |file|
file << <<-eos
#include "#{@mruby_dir}/include/mruby.h"
#include "#{@mruby_dir}/include/mruby/irep.h"
#include "#{@mruby_dir}/include/mruby/proc.h"
int
main(void)
{
mrb_state *mrb;
mrb = mrb_open();
int n = mrb_read_irep(mrb, #{@file});
mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb));
mrb_close(mrb);
return 0;
}
eos
end
end
def compile_and_link
`gcc -I#{@mruby_dir}/mruby/src -I#{@mruby_dir}/include -c #{@file}.c -o #{@file}.o`
`gcc -o #{@file} #{@file}.o #{@mruby_dir}/build/host/lib/libmruby.a`
end
end
Compiler.new.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment