How do I get a stack trace in OCaml?
-
02-07-2019 - |
Question
The Objective Caml language will only produce stack traces if you ask for them just right - what are the requirements for both bytecode and native code?
Solution
Compile with -g and set environment variable OCAMLRUNPARAM=b
OTHER TIPS
Some Printexc functions let you do this programmatically.
Because it looks like you can only get traces for exceptions on unix you can fork and throw the exception in the second process. This way the main process can continue:
export OCAMLRUNPARAM=b
# compile with -g
flush_all(); let r = Unix.fork() in if r == 0 then raise Exit
If you are using Ocamlbuild instead of invoking compiler directly, you can use the debug
tag. From the manual:
With OCamlbuild, you can simply add the debug tag to your program’s targets, and it will sort out when to insert the -g flag or not.
For example, if you are building a file foo.ml
with package bar
then your _tags
file will have a line:
<foo.ml>: package(bar), debug
This will insert the appropriate -g
flags while building bytecode/native files. However, you still need to set the environment variable using export OCAMLRUNPARAM=b
as mentioned in the other answers.