zig-debugging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zig Debugging

Zig调试

Purpose

用途

Guide agents through debugging Zig programs: GDB/LLDB sessions, interpreting Zig panics and error return traces,
std.debug.print
logging, debug build configuration, and IDE integration.
指导开发者完成Zig程序的调试工作:包括GDB/LLDB会话、解析Zig panic和错误返回追踪、
std.debug.print
日志记录、调试构建配置以及IDE集成。

Triggers

触发场景

  • "How do I debug a Zig program with GDB?"
  • "How do I interpret a Zig panic message?"
  • "How do I use std.debug.print for debugging?"
  • "Zig is showing an error return trace — what does it mean?"
  • "How do I set up Zig debugging in VS Code?"
  • "How do I get a stack trace from a Zig crash?"
  • "如何使用GDB调试Zig程序?"
  • "如何解析Zig panic信息?"
  • "如何使用std.debug.print进行调试?"
  • "Zig显示了错误返回追踪——这是什么意思?"
  • "如何在VS Code中设置Zig调试?"
  • "如何从Zig崩溃中获取堆栈追踪?"

Workflow

工作流程

1. Build for debugging

1. 构建调试版本

bash
undefined
bash
undefined

Debug build (default) — full debug info, safety checks

调试构建(默认)——包含完整调试信息、安全检查

zig build-exe src/main.zig -O Debug
zig build-exe src/main.zig -O Debug

With build system

使用构建系统

zig build # uses Debug by default zig build -Doptimize=Debug
zig build # 默认使用Debug模式 zig build -Doptimize=Debug

Run directly with debug output

直接运行并输出调试信息

zig run src/main.zig
undefined
zig run src/main.zig
undefined

2. GDB with Zig

2. 结合GDB调试Zig

Zig emits standard DWARF debug information compatible with GDB:
bash
undefined
Zig会生成兼容GDB的标准DWARF调试信息:
bash
undefined

Build with debug info

构建包含调试信息的程序

zig build-exe src/main.zig -O Debug -femit-bin=myapp
zig build-exe src/main.zig -O Debug -femit-bin=myapp

Launch GDB

启动GDB

gdb ./myapp
gdb ./myapp

GDB session

GDB会话操作

(gdb) break main (gdb) run arg1 arg2 (gdb) next # step over (gdb) step # step into (gdb) continue (gdb) print my_var (gdb) info locals (gdb) bt # backtrace

Break on Zig panics:
```gdb
(gdb) break __zig_panic_start
(gdb) break std.builtin.default_panic
(gdb) break main (gdb) run arg1 arg2 (gdb) next # 单步跳过 (gdb) step # 单步进入 (gdb) continue (gdb) print my_var (gdb) info locals (gdb) bt # 查看堆栈回溯

设置Zig panic断点:
```gdb
(gdb) break __zig_panic_start
(gdb) break std.builtin.default_panic

3. LLDB with Zig

3. 结合LLDB调试Zig

bash
lldb ./myapp

(lldb) b main
(lldb) r arg1 arg2
(lldb) n            # next
(lldb) s            # step into
(lldb) p my_var     # print
(lldb) frame variable
(lldb) bt           # backtrace
(lldb) c            # continue
bash
lldb ./myapp

(lldb) b main
(lldb) r arg1 arg2
(lldb) n            # 单步跳过
(lldb) s            # 单步进入
(lldb) p my_var     # 打印变量
(lldb) frame variable
(lldb) bt           # 查看堆栈回溯
(lldb) c            # 继续执行

Break on panic

设置panic断点

(lldb) b __zig_panic
undefined
(lldb) b __zig_panic
undefined

4. Interpreting Zig panics

4. 解析Zig panic信息

Zig panics include the source location and reason:
thread 'main' panic: index out of bounds: index 5, len 3
/home/user/src/main.zig:15:14
/home/user/src/main.zig:42:9
???:?:?: (name not available)
Common panic messages:
PanicCause
index out of bounds: index N, len M
Slice/array OOB access
integer overflow
Arithmetic overflow in Debug/ReleaseSafe
attempt to unwrap null
Optional access
.?
on null
reached unreachable code
unreachable
executed
casting...
Invalid enum tag or union access
integer cast truncated bits
@intCast
with value out of range
out of memory
Allocator failed
Zig panic会包含源码位置和原因:
thread 'main' panic: index out of bounds: index 5, len 3
/home/user/src/main.zig:15:14
/home/user/src/main.zig:42:9
???:?:?: (name not available)
常见panic信息及原因:
Panic信息原因
index out of bounds: index N, len M
切片/数组越界访问
integer overflow
Debug/ReleaseSafe模式下算术溢出
attempt to unwrap null
对null值使用
.?
解包
reached unreachable code
执行了
unreachable
语句
casting...
无效的枚举标签或联合类型访问
integer cast truncated bits
@intCast
转换的值超出目标类型范围
out of memory
内存分配器分配失败

5. Error return traces

5. 错误返回追踪

Zig tracks where errors propagate with error return traces:
error: FileNotFound
/home/user/src/main.zig:30:20: 0x10a3b in openConfig (main)
    const f = try std.fs.openFileAbsolute(path, .{});
                   ^
/home/user/src/main.zig:15:25: 0x10b12 in run (main)
    const cfg = try openConfig("/etc/myapp.conf");
                    ^
/home/user/src/main.zig:8:20: 0x10c44 in main (main)
    try run();
               ^
The trace shows the exact
try
chain where the error propagated. Read bottom-up:
main → run → openConfig
.
Enable in release builds:
zig
// build.zig
const exe = b.addExecutable(.{
    .name = "myapp",
    .root_source_file = b.path("src/main.zig"),
    .target = target,
    .optimize = optimize,
    .error_tracing = true,  // enable even in ReleaseFast
});
Zig会追踪错误传播路径并生成错误返回追踪:
error: FileNotFound
/home/user/src/main.zig:30:20: 0x10a3b in openConfig (main)
    const f = try std.fs.openFileAbsolute(path, .{});
                   ^
/home/user/src/main.zig:15:25: 0x10b12 in run (main)
    const cfg = try openConfig("/etc/myapp.conf");
                    ^
/home/user/src/main.zig:8:20: 0x10c44 in main (main)
    try run();
               ^
追踪信息显示了
try
链的传播路径,从下往上读:
main → run → openConfig
在Release构建中启用错误追踪:
zig
// build.zig
const exe = b.addExecutable(.{
    .name = "myapp",
    .root_source_file = b.path("src/main.zig"),
    .target = target,
    .optimize = optimize,
    .error_tracing = true,  // 即使在ReleaseFast模式下也启用
});

6. std.debug.print for tracing

6. 使用std.debug.print进行追踪

zig
const std = @import("std");

pub fn main() !void {
    const x: u32 = 42;
    const name = "world";

    // Basic print (always to stderr)
    std.debug.print("x = {d}, name = {s}\n", .{ x, name });

    // Print any value (useful for structs)
    const point = Point{ .x = 1, .y = 2 };
    std.debug.print("point = {any}\n", .{point});

    // Formatted output
    std.debug.print("hex: {x}, binary: {b}\n", .{ x, x });

    // Log levels (respects compile-time log level)
    const log = std.log.scoped(.my_module);
    log.debug("debug info: {d}", .{x});
    log.info("started processing", .{});
    log.warn("unusual condition", .{});
    log.err("failed: {s}", .{"reason"});
}
zig
const std = @import("std");

pub fn main() !void {
    const x: u32 = 42;
    const name = "world";

    // 基础打印(始终输出到stderr)
    std.debug.print("x = {d}, name = {s}\n", .{ x, name });

    // 打印任意值(适用于结构体)
    const point = Point{ .x = 1, .y = 2 };
    std.debug.print("point = {any}\n", .{point});

    // 格式化输出
    std.debug.print("hex: {x}, binary: {b}\n", .{ x, x });

    // 日志级别(遵循编译时日志级别设置)
    const log = std.log.scoped(.my_module);
    log.debug("调试信息: {d}", .{x});
    log.info("处理已启动", .{});
    log.warn("异常情况", .{});
    log.err("执行失败: {s}", .{"原因"});
}

7. std.log configuration

7. std.log配置

zig
// Override default log level at root
pub const std_options = std.Options{
    .log_level = .debug,  // .debug | .info | .warn | .err
};

// Custom log handler
pub fn logFn(
    comptime level: std.log.Level,
    comptime scope: @TypeOf(.enum_literal),
    comptime format: []const u8,
    args: anytype,
) void {
    const prefix = "[" ++ @tagName(level) ++ "] (" ++ @tagName(scope) ++ "): ";
    std.debug.print(prefix ++ format ++ "\n", args);
}

pub const std_options = std.Options{
    .logFn = logFn,
};
zig
// 全局覆盖默认日志级别
pub const std_options = std.Options{
    .log_level = .debug,  // .debug | .info | .warn | .err
};

// 自定义日志处理器
pub fn logFn(
    comptime level: std.log.Level,
    comptime scope: @TypeOf(.enum_literal),
    comptime format: []const u8,
    args: anytype,
) void {
    const prefix = "[" ++ @tagName(level) ++ "] (" ++ @tagName(scope) ++ "): ";
    std.debug.print(prefix ++ format ++ "\n", args);
}

pub const std_options = std.Options{
    .logFn = logFn,
};

8. VS Code / IDE integration

8. VS Code / IDE集成

Install the
zig.vscode-zig
extension and CodeLLDB.
.vscode/launch.json
:
json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug Zig",
            "program": "${workspaceFolder}/zig-out/bin/myapp",
            "args": [],
            "cwd": "${workspaceFolder}",
            "preLaunchTask": "zig build"
        }
    ]
}
.vscode/tasks.json
:
json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "zig build",
            "type": "shell",
            "command": "zig build",
            "group": { "kind": "build", "isDefault": true },
            "problemMatcher": ["$zig"]
        }
    ]
}
安装
zig.vscode-zig
扩展和CodeLLDB。
.vscode/launch.json
:
json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "调试Zig",
            "program": "${workspaceFolder}/zig-out/bin/myapp",
            "args": [],
            "cwd": "${workspaceFolder}",
            "preLaunchTask": "zig build"
        }
    ]
}
.vscode/tasks.json
:
json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "zig build",
            "type": "shell",
            "command": "zig build",
            "group": { "kind": "build", "isDefault": true },
            "problemMatcher": ["$zig"]
        }
    ]
}

Related skills

相关技能

  • Use
    skills/zig/zig-compiler
    for build modes and debug info flags
  • Use
    skills/debuggers/gdb
    for GDB fundamentals
  • Use
    skills/debuggers/lldb
    for LLDB fundamentals
  • Use
    skills/zig/zig-cinterop
    when debugging mixed Zig/C code
  • 如需了解构建模式和调试信息标志,请使用
    skills/zig/zig-compiler
  • 如需了解GDB基础,请使用
    skills/debuggers/gdb
  • 如需了解LLDB基础,请使用
    skills/debuggers/lldb
  • 如需调试Zig/C混合代码,请使用
    skills/zig/zig-cinterop