Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile ocaml to native code

i'm really interested learning ocaml, it fast (they said it could be compiled to native code) and it's functional. So i tried to code something easy like enabling mysql event scheduler.

#load "unix.cma";;
#directory "+mysql";;
#load "mysql.cma";;
let db = Mysql.quick_connect
  ~user:"username"
  ~password:"userpassword"
  ~database:"databasename"();;
let sql =
    "SET GLOBAL EVENT_SCHEDULER=1;"
    in
    (Mysql.exec db sql);;

It work fine on ocaml interpreter, but when i was trying to compile it to native (i'm using ubuntu karmic), neither of these command worked

ocamlopt -o mysqleventon mysqleventon.ml unix.cmxa mysql.cmxa
ocamlopt -o mysqleventon mysqleventon.ml unix.cma mysql.cma

i also tried

ocamlc -c mysqleventon.ml unix.cma mysql.cma

all of them resulting same message

File "mysqleventon.ml", line 1, characters 0-1:
Error: Syntax error

Then i tried to remove the "# load", so the code goes like this

let db = Mysql.quick_connect
  ~user:"username"
  ~password:"userpassword"
  ~database:"databasename"();;
let sql =
    "SET GLOBAL EVENT_SCHEDULER=1;"
    in
    (Mysql.exec db sql);;

The ocamlopt resulting message

File "mysqleventon.ml", line 1, characters 9-28:
Error: Unbound value Mysql.quick_connect

I hope someone could tell me, where did i'm doing wrong.

like image 676
Indra Ginanjar Avatar asked Apr 20 '10 04:04

Indra Ginanjar


1 Answers

#load and #directory are the toplevel directives. They instruct ocaml where to find mysql and unix libraries. For native (or bytecode) compilation remove those directives and replace them with corresponding command-line flags. #load maps just to the file name and #directory to -I. So for bytecode:

ocamlc unix.cma -I +mysql mysql.cma mysqleventon.ml -o mysqleventon

Native code:

ocamlopt unix.cmxa -I +mysql mysql.cmxa -o mysqleventon mysqleventon.ml

NB: .cmxa is for native code, .cma for bytecode. Also the order of filenames on command-line matters.

Or better use ocamlfind and don't worry about paths and extensions :

ocamlfind ocamlopt -package unix,mysql -linkpkg mysqleventon.ml -o mysqleventon 
like image 104
ygrek Avatar answered Nov 20 '22 07:11

ygrek