0

Zig version

0.11.0-dev.3299+34865d693

The problem

I want to be able to see the assembly output of my program, ideally with file names and line numbers mapping to the assembly instructions so I can quickly reason about where they've come from.

Files in project

build.zig

const std = @import("std");

pub fn build(b: *std.Build.Builder) !void {
    // Determine compilation target
    const target = b.standardTargetOptions(.{});

    // Setup optimisation settings
    const optimize = b.standardOptimizeOption(.{});

    // Create executable for our example
    const exe = b.addExecutable(.{
        .name = "app",
        .root_source_file = .{ .path = "main.zig" },
        .target = target,
        .optimize = optimize,
    });

    // Install the executable into the prefix when invoking "zig build"
    b.installArtifact(exe);
}

main.zig

const std = @import("std");

pub fn main() void {
    std.debug.print("Hello, {s}!\n", .{"World"});
}
SilbinaryWolf
  • 461
  • 4
  • 9

2 Answers2

3

Update your build.zig to emit assembly by adding the following to your build settings. This will make Zig output an "app.s" file.

// Get assembly output of build
exe.emit_asm = .emit;

As far as I know, there's seemingly no way to get file names and line numbers associated with the assembly instructions at this time.

Full example:

const std = @import("std");

pub fn build(b: *std.Build.Builder) !void {
    // Determine compilation target
    const target = b.standardTargetOptions(.{});

    // Setup optimisation settings
    const optimize = b.standardOptimizeOption(.{});

    // Create executable for our example
    const exe = b.addExecutable(.{
        .name = "app",
        .root_source_file = .{ .path = "main.zig" },
        .target = target,
        .optimize = optimize,
    });

    // Install the executable into the prefix when invoking "zig build"
    b.installArtifact(exe);

    // Get assembly output of build
    exe.emit_asm = .emit;
}

Snippet of assembly output:

main.main:
.Lfunc_begin6:
    .cv_func_id 8
    .cv_file    5 "C:\\ZigProjects\\hello-world\\main.zig"
    .cv_loc 8 5 3 0
.seh_proc main.main
    push    rbp
    .seh_pushreg rbp
    sub rsp, 32
    .seh_stackalloc 32
    lea rbp, [rsp + 32]
    .seh_setframe rbp, 32
    .seh_endprologue
.Ltmp22:
    .cv_loc 8 5 4 20
    call    debug.print__anon_2816
    nop
    add rsp, 32
    pop rbp
    ret
SilbinaryWolf
  • 461
  • 4
  • 9
0

in addition to the answer above you can always debug the disassembly using gdb if want to walk through and see what happens exactly.

Abdelhadi
  • 1
  • 1