# Exercises

### Exercises

This section collects the chapter exercises into one working set.

Exercise 17-1. Run:

```sh
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:

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

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

```zig
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:

```zig
const builtin = @import("builtin");

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

Exercise 17-5. Print the pointer size:

```zig
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:

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

Compare the result with a glibc build:

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

Exercise 17-7. Write a C function:

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

Call it from Zig:

```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:

```sh
zig build-exe main.zig add.c
```

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

```sh
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:

```zig
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:

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

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

