There are two common ways to run a small Zig program.
The first way is direct:
zig run main.zigThis compiles main.zig, runs the result, and then removes the temporary executable. It is useful while learning.
For example:
const std = @import("std");
pub fn main() void {
std.debug.print("hello, zig\n", .{});
}Run it:
zig run main.zigThe output is:
hello, zigThe second way is to build an executable:
zig build-exe main.zigThis produces a program file in the current directory.
On Unix-like systems, the file is usually named:
mainRun it:
./mainOn Windows, the file is usually named:
main.exeRun it:
main.exezig 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:
zig build-exe main.zig -femit-bin=helloNow the executable is named hello.
Run it:
./helloA Zig source file does not need a project directory. One file is enough:
main.zigA 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:
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:
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.