Search code examples
crubycompilationmruby

How to compile an mruby example?


Hearing about mruby has inspired me to start learning C programming. I have worked through a few tutorials online so I understand the basics, but now I would like to start playing with mruby by compiling an example application. I understand how to compile a single C file, but I'm stuck at trying to figure out how to also compile mruby along with my own code.

I'm using GCC on Mac OS X 10.8.

Using this example:

#include <stdlib.h>
#include <stdio.h>

#include <mruby.h>
#include <mruby/compile.h>

int main(void)
{
  mrb_state *mrb = mrb_open();
  char code[] = "p 'hello world!'";
  printf("Executing Ruby code from C!\n");

  mrb_load_string(mrb, code);
  return 0;
}

And running this command:

gcc example.c

I obviously get the error:

engine.c:4:19: error: mruby.h: No such file or directory

I have cloned the git repo and created a symlink to the include directory, but I'm pretty sure I'm doing it wrong.

How should I include mruby in my code so that it's all compiled together?

Update: Here is the directory structure of what I have, note the symlink to the mruby include directory:

$ tree -l .
.
├── example.c
└── include
    └── mruby -> ../../mruby/include
        ├── mrbconf.h
        ├── mruby
        │   ├── array.h
        │   ├── class.h
        │   ├── compile.h
        │   ├── data.h
        │   ├── debug.h
        │   ├── dump.h
        │   ├── gc.h
        │   ├── hash.h
        │   ├── irep.h
        │   ├── khash.h
        │   ├── numeric.h
        │   ├── proc.h
        │   ├── range.h
        │   ├── string.h
        │   ├── value.h
        │   └── variable.h
        └── mruby.h

When I compile by including the directory:

gcc example.c -I include/mruby

I get the following errors:

Undefined symbols for architecture x86_64:
  "_mrb_load_string", referenced from:
      _main in ccd8XYkm.o
  "_mrb_open", referenced from:
      _main in ccd8XYkm.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Update: I followed the instructions in the mruby/INSTALL file (which basically just said run make in the root directory of the mruby project). This added a bunch of directories and field in the mruby/build/host directory, including the file lib/libmruby.a. I was able to compile the example script by including this file when compiling.

gcc -Iinclude/mruby example.c ../mruby/build/host/lib/libmruby.a

Now I run my app:

$ ./a.out
Executing Ruby code from C!
"hello world!"

Solution

  • Instead of

    #include <mruby.h>
    #include <mruby/compile.h>
    

    Try

    #include "mruby.h"
    #include "mruby/compile.h"
    

    Let me know if that makes any difference. The compiler uses different search paths for includes with <> and "". "" are local.

    You can also try

    gcc -Ipath/to/ruby/include/dir example.c