# Installing Zig and Using the Toolchain — Zig

Source: https://www.geekswithgeeks.com/en/zig/f-setup

> Install Zig, create a project and use run, build, test and fmt.

## One binary, many tools

Zig ships as a **single self-contained archive**: download it from ziglang.org, use a package manager, or use a version manager such as **zvm**, **zigup** or **anyzig** to switch versions per project. The `zig` command contains everything: **`zig run file.zig`** compiles and runs a file, **`zig build-exe`** builds an executable, **`zig test file.zig`** runs the tests in a file, and **`zig fmt`** formats code in the one official style. **`zig init`** creates a project with **`build.zig`** (the build script, written in Zig) and **`build.zig.zon`** (package metadata and dependencies), plus `src/main.zig` and `src/root.zig`. Then `zig build` compiles, `zig build run` runs and `zig build test` tests. **Build modes** are chosen with `-O` or `-Doptimize=`: **Debug** (default, safety checks, fast compile), **ReleaseSafe** (optimised, safety checks kept), **ReleaseFast** (optimised, safety checks removed) and **ReleaseSmall** (optimised for size). The **ZLS** language server provides editor support. Zig's own compiler is increasingly self-hosted, with its own fast backend for Debug builds on some targets alongside LLVM.

## Creating and running a project

zig init, build modes and the project layout.

```bash
zig version                     # e.g. 0.15.x
mkdir invoices && cd invoices
zig init                        # creates build.zig, build.zig.zon, src/main.zig, src/root.zig

zig build run                   # build (Debug) and run
zig build test                  # run unit tests
zig build -Doptimize=ReleaseSafe   # optimised, safety checks kept
zig fmt src/                    # format all files

# single files without a project
zig run src/main.zig
zig test src/root.zig
zig build-exe src/main.zig -O ReleaseFast

# layout
# invoices/
#   build.zig        build script (Zig code)
#   build.zig.zon    package name, version, dependencies
#   src/main.zig     executable entry point
#   src/root.zig     library module and its tests
```

## A Swiss army knife

Where C projects need a compiler, a build system, a package manager, a formatter and cross-compilers from different vendors, the zig binary is one Swiss army knife that folds all of them into a single tool.

**Quiz:** Which build mode keeps runtime safety checks while optimising?

- [ ] Debug
- [ ] ReleaseFast
- [ ] ReleaseSmall
- [x] ReleaseSafe

*Answer:* ReleaseSafe. ReleaseSafe optimises but keeps bounds and overflow checks.
