How do I get a stack trace in OCaml?
Asked Answered
S

5

39

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?

Snowmobile answered 28/9, 2008 at 13:53 Comment(0)
S
46

Compile with -g and set environment variable OCAMLRUNPARAM=b

Snowmobile answered 28/9, 2008 at 13:56 Comment(3)
For native code, I believe this only works for OCaml v3.10 or later.Hessian
How to do this with dune build system?Fairtrade
@OlleHärstedt see #65869270Denial
S
11

Some Printexc functions let you do this programmatically.

Shavers answered 1/2, 2010 at 15:5 Comment(1)
Specifically Printexc.record_backtrace true.Huang
R
5

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
Repress answered 23/6, 2013 at 0:54 Comment(0)
Y
3

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.

Younger answered 30/7, 2017 at 3:23 Comment(0)
F
0

As noted in other answers, you need to compile your project with debugging info and run it with the OCAMLRUNPARAM=b environment variable.

A convenient way to have Ocamlbuild compile an entire project with debugging info but without editing the _tags file is to specify a special debug target. From the manual:

The preferred way of compiling code suitable for debugging with ocamldebug or profiling native code with ocamlprof is to use the appropriate target extensions, .d.byte for debugging or .p.native.

I use this technique for quick compile-run cycles on the command line. For example, to run foo.ml:

export OCAMLRUNPARAM=b

ocamlbuild -no-links foo.d.byte && _build/foo.d.byte
Fugleman answered 22/8, 2021 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.