Skip to content

Exercises

This section collects the chapter exercises into one working set.

This section collects the chapter exercises into one working set.

Exercise 17-1. Run:

zig targets

Find five architectures and five operating systems in the output.

Exercise 17-2. Compile the same program for your native target and for Linux x86-64:

zig build-exe main.zig
zig build-exe main.zig -target x86_64-linux-gnu

Exercise 17-3. Print the architecture and operating system:

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

pub fn main() void {
    std.debug.print("arch = {s}\n", .{@tagName(builtin.cpu.arch)});
    std.debug.print("os   = {s}\n", .{@tagName(builtin.os.tag)});
}

Exercise 17-4. Add a function that returns the path separator for the target:

const builtin = @import("builtin");

fn pathSeparator() u8 {
    return switch (builtin.os.tag) {
        .windows => '\\',
        else => '/',
    };
}

Exercise 17-5. Print the pointer size:

const std = @import("std");

pub fn main() void {
    std.debug.print("{d}\n", .{@bitSizeOf(usize)});
}

Build it for a 64-bit target and a 32-bit target.

Exercise 17-6. Build for musl:

zig build-exe main.zig -target x86_64-linux-musl

Compare the result with a glibc build:

zig build-exe main.zig -target x86_64-linux-gnu

Exercise 17-7. Write a C function:

int add(int a, int b) {
    return a + b;
}

Call it from Zig:

const std = @import("std");

extern fn add(a: c_int, b: c_int) c_int;

pub fn main() void {
    std.debug.print("{d}\n", .{add(20, 22)});
}

Build both files together:

zig build-exe main.zig add.c

Exercise 17-8. Build the same program in all four optimization modes:

zig build-exe main.zig -O Debug
zig build-exe main.zig -O ReleaseSafe
zig build-exe main.zig -O ReleaseFast
zig build-exe main.zig -O ReleaseSmall

Exercise 17-9. Print the selected mode:

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

pub fn main() void {
    std.debug.print("mode = {s}\n", .{@tagName(builtin.mode)});
}

Exercise 17-10. Write a short note explaining the difference between these targets:

x86_64-linux-gnu
x86_64-linux-musl
x86_64-linux-none
wasm32-freestanding-none

Use concrete terms: architecture, operating system, and ABI.