# Build and Run

### Build and Run

There are two common ways to run a small Zig program.

The first way is direct:

```sh
zig run main.zig
```

This compiles `main.zig`, runs the result, and then removes the temporary executable. It is useful while learning.

For example:

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

pub fn main() void {
    std.debug.print("hello, zig\n", .{});
}
```

Run it:

```sh
zig run main.zig
```

The output is:

```text
hello, zig
```

The second way is to build an executable:

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

This produces a program file in the current directory.

On Unix-like systems, the file is usually named:

```text
main
```

Run it:

```sh
./main
```

On Windows, the file is usually named:

```text
main.exe
```

Run it:

```cmd
main.exe
```

`zig run` is a shortcut. It compiles and runs in one command.

`zig build-exe` keeps the executable. Use it when you want the output file.

You can also choose the output name:

```sh
zig build-exe main.zig -femit-bin=hello
```

Now the executable is named `hello`.

Run it:

```sh
./hello
```

A Zig source file does not need a project directory. One file is enough:

```text
main.zig
```

A larger program usually uses the build system. A small program can start with one command and one file.

The compiler reads the source file, checks the program, and writes machine code. If the program has an error, the compiler stops before it creates the executable.

For example:

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

pub fn main() void {
    std.debug.print("hello, zig\n");
}
```

This program is wrong. `std.debug.print` needs two arguments. The format string is first. The value tuple is second.

Write it this way:

```zig
std.debug.print("hello, zig\n", .{});
```

The compiler is part of the programming model. It catches many mistakes early. Zig code is usually written by making small changes, compiling often, and reading the error messages carefully.

Exercise 1-5. Build the hello program with `zig run`.

Exercise 1-6. Build the same program with `zig build-exe`.

Exercise 1-7. Change the output executable name to `hello`.

Exercise 1-8. Remove the second argument to `std.debug.print` and read the compiler error.

