Jon Smark
Jon Smark

Reputation: 2608

Printing current call stack in OCaml

Is there a way in OCaml to get the current call stack programatically? By this, I do not mean inside a debugger but as a function call inside the program that will print the current call stack. I imagine this should not be beyond the capabilities of the byte-code interpreter, especially if debug symbols are available.

Upvotes: 12

Views: 1947

Answers (4)

user1971598
user1971598

Reputation:

I came to this question looking for the same thing, here's my solution

Printexc.get_callstack 5 |> Printexc.raw_backtrace_to_string

(Its actually a pretty good way to familiarize yourself with a new code base)

Upvotes: 11

Ontologiae
Ontologiae

Reputation: 605

You can also use ocamldebug, with which you can start your code, compiled in bytecode. In this environment, Printexc.get_backtrace () are far more completes.

Upvotes: 1

Fabrice Le Fessant
Fabrice Le Fessant

Reputation: 4274

Unfortunately, the only way to get a backtrace from inside the code is when an exception is raised, you can then use Printexc.get_backtrace (). It won't give you though the names of the functions, just the locations in the code of what is in the stack, and only if OCaml was able to recover them...

Upvotes: 0

ygrek
ygrek

Reputation: 6697

For native code one can use glibc's backtrace, though it may not print all stack frames correctly.

Upvotes: 0

Related Questions