Tutorial part 1: "Hello world" - nojb/ocaml-gccjit GitHub Wiki

Before we look at the details of the API, let's look at building and running programs that use the library.

Here's a toy "hello world" program that uses the library to synthetize a call to printf and uses it to write a message to stdout.

(* Smoketest example for libgccjit.so *)

open Gccjit

(* Let's try to inject the equivalent of:

     void
     greet (const char *name)
     {
        printf ("hello %s\n", name);
     } *)
let create_code ctx =
  let void_type = Type.(get ctx Void) in
  let const_char_ptr_type = Type.(get ctx Const_char_ptr) in
  let param_name = Param.create ctx const_char_ptr_type "name" in
  let func = Function.create ctx Function.Exported void_type "greet" [ param_name ] in
  let param_format = Param.create ctx const_char_ptr_type "format" in
  let printf_func =
    Function.create ctx ~variadic:true Function.Imported (Type.get ctx Int) "printf" [ param_format ]
  in
  let hello = RValue.string_literal ctx "hello %s\n" in
  let block = Block.create func in
  Block.eval block (RValue.call ctx printf_func [ hello; RValue.param param_name ]);
  Block.return_void block

let () =
  (* Get a "context" object for working with the library. *)
  let ctx = Context.create () in

  (* Set some options on the context.
     Let's see the code being generated, in assembler form. *)
  Context.set_option ctx Context.Dump_generated_code false;

  (* Populate the context. *)
  create_code ctx;

  (* Compile the code. *)
  let result = Context.compile ctx in

  (* Extract the generated code from "result". *)
  let greet = Result.code result "greet" Ctypes.(string @-> returning void) in

  (* Now call the generated function: *)
  greet "world";
  flush stdout;

  Context.release ctx;
  Result.release result

Copy the above to tut01_hello_world.ml.

Assuming you have the jit library installed, build the test program using:

$ ocamlbuild -use-ocamlfind -package gccjit tut01_hello_world.native

You should then be able to run the built program:

$ ./tut01_hello_world.native
hello world