How to print caller's file&line number at runtime?

There is: std.debug.printSourceAtAddress that prints filename, line number, and the source code line if it is available.
Example:

❯ cat test.zig
const std = @import("std");

pub fn main() !void {
    const info = try std.debug.getSelfDebugInfo();
    const addr = @returnAddress();
    const out = std.io.getStdErr();
    const tty = std.io.tty.detectConfig(out);
    try std.debug.printSourceAtAddress(info, out.writer(), addr, tty);
}

❯ zig run test.zig
/home/din/zig/0.13.0/lib/std/start.zig:524:37: 0x1034b36 in posixCallMainAndExit (test)
            const result = root.main() catch |err| {
                                    ^

5 Likes