ocamldep-sorter — dependencies sorter for OCaml

See also: ocamldsort

Have you ever got this message?

File "_none_", line 1, characters 0-1:
Error: Error while linking some_module.cmo:
Reference to undefined global `Another_module'

It happens every time when you link .cmo’s or .cmx’es in wrong order.

Another problem: you can’t just take wildcard *.cmo and build your binary, you have to specify each file in the right order.

I gave up when I was creating a webapp with lots of ECaml templates. So I decided to write a tool that parses ocamldep output and provides a nice sequence for ocamlc -linkpkg.

Download

git clone https://github.com/apsheronets/ocamldep-sorter.git

How it works?

$ ls *.ml
first.ml  second.ml  third.m
$ ocamldep *.ml > depend
$ cat depend
first.cmo:
first.cmx:
second.cmo: first.cmo
second.cmx: first.cmx
third.cmo: second.cmo first.cmo
third.cmx: second.cmx first.cmx
$ ocamldep-sorter < depend
first.cmo first.cmx second.cmo second.cmx third.cmo third.cmx
$ ocamldep-sorter second.cmx first.cmx < depend
first.cmx second.cmx

Makefile example

Pay attention to second line — I just do ls *.ml:

packages = extlib
files = $(shell ls *.ml)
name = grapher

camlc   = ocamlfind ocamlc   $(lib)
camlopt = ocamlfind ocamlopt $(lib)
camldep = ocamlfind ocamldep
lib = -package $(packages)

objs    = $(files:.ml=.cmo)
optobjs = $(files:.ml=.cmx)

all: $(name)

$(name): $(optobjs)
  $(camlopt) `ocamldep-sorter $^ < .depend` -linkpkg -o $@

.SUFFIXES: .ml .mli .cmo .cmi .cmx

.ml.cmo:
  $(camlc) -c $<
.mli.cmi:
  $(camlc) -c $<
.ml.cmx:
  $(camlopt) -c $<

clean:
  -rm -f *.cm[ioxa] *.cmx[as] *.o *.a *~ $(name)
  -rm -f .depend

.depend: $(files)
  $(camldep) $(lib) $(files:.ml=.mli) $(files) > .depend

FORCE:

-include .depend

This is not just an example: I use this Makefile to build my divananalit.org website.