I’m thinking of doing some home projects for doing stuff like driving LEDs from a Raspberry Pi using OCaml. Is there a good way of doing this with a cross compiler via OCaml? Or do I need to install OCaml and build my executables on the Pi? I know that there was some work to get cross compilation working properly with Dune, but I don’t know how to do it in practice.
Currently, the cross compilation story with dune is as follow: once you have setup one of the cross-compiling environments available on https://github.com/ocaml-cross, you can cross-compile with dune as follow:
$ dune build -x windows,android,ios ...
This will create _build/default.windows, _build/default.android and so on.
The longest step is building/installing the cross-compiler. You don’t need a special dune to cross compile.
If you’re working on a Mac/Win, then a cheap and cheerful way to get an rPI-compatible environment is to use Docker for Mac/Win, which transparently do CPU emulation via qemu-user-static and binfmt.
$ docker run -it ocaml/opam2-staging:debian-9-ocaml-4.08-linux-arm32v7
opam@fdd0cc1ae238:~/opam-repository$ uname -a
Linux fdd0cc1ae238 4.9.125-linuxkit #1 SMP Fri Sep 7 08:20:28 UTC 2018 armv7l GNU/Linux
opam@fdd0cc1ae238:~/opam-repository$ ocamlc -config|grep arch
architecture: arm
opam@fdd0cc1ae238:~/opam-repository$ opam install -y dune
<...etc>
You can save the binary results of the build by adding a -v <yourrepo>:/home/opam/src to mount a local volume within the ARM container. This will be a pretty slow option, but probably faster than compiling within the rPi3.
I know this thread is over 4 years old by now, but I was wondering if this is still the best way to cross compile for a different architectures? My goal is to compile from a M1 or a linux (x64) box to a raspberry pi 4, which I have lying around.
Since you seem to be interested in cross-compiling specifically to experiment on a RPi, let me come back to the context of the dbuenzli/rpi-boot-ocaml pointer above: Nowadays, you could cross-compile to a bare metal RPi, using @dinosaure’s toolchain gilbraltar. I admit that bare metal is a bit limited and it’s quite nice to have drivers around but also, it’s surprising how much can be done from scratch! E.g. @Lortex and others power LED strips bare metal over the UART and play music bare metal over the jack port in well-typed-light-bulbs/rpi.