Hello World (first programs) · Beginner · 16 min
Hello World in Zig: zig run, zig build and zig cc
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Zig 0.17.1
You will install a signature-checked Zig 0.17.1 on Ubuntu 26.04, write and run Hello World with the current I/O API, build a small project with zig build that handles errors explicitly, and use zig cc to compile a C program for Linux and for Windows.
On this page
Zig is a systems language in the same space as C and Rust: it compiles to machine code, has no garbage collector, and lets you decide where every byte of memory comes from. Its promise is that what you read is what runs. There are no hidden memory allocations (any function that allocates takes an allocator as an argument), no hidden control flow (no exceptions, no operator overloading, no constructors running behind your back), and errors are values you must handle or pass on, never ignore by accident.
Two more things make Zig unusual. comptime lets ordinary Zig code run while the program compiles, which is how Zig does generics and how print checks its format string before the program ever runs. And the zig download carries a complete C and C++ compiler, zig cc, with the headers and libraries needed to build for Linux, macOS and Windows from any one of them. Many people install Zig for that alone.
Zig is not at version 1.0 yet. Each release still changes parts of the standard library, and the way programs write output changed in both 0.15 and 0.16. Code from older blog posts often no longer compiles. Everything here is written for Zig 0.17.1, from November 2026.
You work in a throwaway folder, ~/hello-zig-demo, and delete it at the end.
Step 1 · Download Zig and check its signature
Zig is not in Ubuntu's own package list at a current version, so you download the official release archive. The Zig project signs every archive with minisign, a small signing tool. Checking the signature proves the file came from the Zig team and was not changed on the way.
Install the tools you need, pick the archive for your processor, and download it with its signature file:
sudo apt update
sudo apt install -y curl ca-certificates xz-utils minisign file
VERSION=0.17.1
case "$(uname -m)" in
x86_64) ARCH=x86_64 ;;
aarch64) ARCH=aarch64 ;;
*) echo "Unsupported processor: $(uname -m)"; false ;;
esac
TARBALL="zig-${ARCH}-linux-${VERSION}.tar.xz"
mkdir -p ~/hello-zig-demo/download
cd ~/hello-zig-demo/download
curl -fSLO "https://ziglang.org/download/${VERSION}/${TARBALL}"
curl -fsSLO "https://ziglang.org/download/${VERSION}/${TARBALL}.minisig"The archive is about 55 MB. On a metered or prepaid connection, download it once and keep the file; the same archive installs on every Ubuntu machine with the same processor type.
Now check the signature against the Zig public key. The key below is the one published on ziglang.org/download; compare it there if you want to be sure this page has not been altered:
minisign -Vm "$TARBALL" -P RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/UCheck it worked
minisign prints Signature and comment signature verified followed by a trusted comment that names the file, such as file:zig-x86_64-linux-0.17.1.tar.xz. If it prints Signature verification failed, stop: delete both files and download them again. Do not unpack an archive that fails this check.
Step 2 · Install Zig in your home folder
Unpack the archive into ~/.local/opt and link the zig program into ~/.local/bin, which Ubuntu puts on your path when that folder exists:
mkdir -p ~/.local/opt ~/.local/bin
tar -xf "$TARBALL" -C ~/.local/opt
ln -sf ~/.local/opt/zig-${ARCH}-linux-${VERSION}/zig ~/.local/bin/zig
export PATH="$HOME/.local/bin:$PATH"
zig versionThe archive is the whole toolchain: the zig program, the standard library source, and the C libraries zig cc needs. Nothing else is installed system-wide, and no root access is used after the apt line. The export line makes the new path work in this shell; new shells pick it up when you next log in.
A file you unpack yourself gets no updates from apt. To upgrade, repeat these two steps with a newer VERSION, and remove the old folder from ~/.local/opt.
On Windows, download the zip for your processor from ziglang.org/download, unpack it and add the folder to your Path, or follow these Ubuntu steps inside WSL. On macOS, download the macOS archive the same way, or use Homebrew (brew install zig), which may lag a release behind.
Check it worked
zig version prints 0.17.1. If you see zig: command not found in a later shell, run the export PATH=... line again or log out and back in.
Step 3 · Write and run hello.zig
Create the source file:
mkdir -p ~/hello-zig-demo
cd ~/hello-zig-demo
cat > hello.zig <<'ZIG'
const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [256]u8 = undefined;
var stdout_writer: std.Io.File.Writer = .init(.stdout(), init.io, &buffer);
const stdout = &stdout_writer.interface;
try stdout.print("Hello, {s}!\n", .{"world"});
try stdout.flush();
}
ZIGEach line, in order:
const std = @import("std");loads the standard library and names itstd. Names starting with@are built-in functions of the compiler.constmeans the name can never point at something else.pub fn main(init: std.process.Init) !void {declares the function the program starts in.pubmakes it visible outside this file, which the start-up code needs. Since Zig 0.16,maincan take aninitvalue that hands you what a program usually needs: command-line arguments, environment variables, memory allocators and anIoobject for input and output.!voidmeans "returns nothing, or an error".var buffer: [256]u8 = undefined;reserves 256 bytes on the stack for output.u8is an unsigned 8-bit number, a byte.undefinedsays you do not care what is in it yet; Zig does not quietly fill it with zeroes for you.varis used because the bytes will change.var stdout_writer: std.Io.File.Writer = .init(.stdout(), init.io, &buffer);creates a writer for standard output that collects text in your buffer..initand.stdout()are short forstd.Io.File.Writer.initandstd.Io.File.stdout(): Zig fills in the type from the left-hand side. Notice that you passed the buffer and theIoobject in yourself. That is the "no hidden allocation" rule in action.const stdout = &stdout_writer.interface;takes a pointer to the general writer interface inside the file writer. Functions that write text accept this interface, so they work the same for files, sockets or memory.try stdout.print("Hello, {s}!\n", .{"world"});formats the text into the buffer.{s}is a placeholder for a string, and.{"world"}is an anonymous list of values to fill in.trymeans "if this returns an error, return it frommainstraight away".try stdout.flush();sends whatever is in the buffer to the terminal. Without it, nothing appears.
Run it with zig run, which compiles the file and runs the result in one go:
zig run hello.zigThe first run takes a few seconds because Zig compiles the parts of the standard library you used. It keeps them in a cache in ~/.cache/zig, so the next run is much faster.
Check it worked
The terminal shows Hello, world!. Change {s} to {d} (the placeholder for a number) and run again: the program does not start, and the compiler reports an error about the format string. That check happened at compile time, because print reads its format string with comptime. Change it back to {s} before you continue.
Step 4 · Compare zig run with zig build-exe
zig run puts the compiled program in the cache and runs it. To get a program file you can keep, copy or ship, use zig build-exe:
cd ~/hello-zig-demo
zig build-exe hello.zig
./hello
file hello
ls -l helloNow build it again with the ReleaseSmall optimisation mode and compare:
zig build-exe -O ReleaseSmall hello.zig
./hello
ls -l helloThe default mode is Debug. It keeps safety checks (for example, a crash with a clear message if you read past the end of an array) and debugging information, so the file is large. ReleaseSafe optimises but keeps the checks. ReleaseFast and ReleaseSmall remove them, optimising for speed and size.
Check it worked
./hello prints Hello, world! both times. file hello describes an ELF executable that is statically linked: on Linux, Zig does not link the C library unless you ask for it, so the program runs on any Linux machine with the same processor type, with nothing else installed. The ReleaseSmall file is many times smaller than the Debug one.
Step 5 · Start a project with zig init and handle an error
For anything bigger than one file, Zig projects use zig build, driven by a build.zig file that is itself written in Zig. Create a project:
mkdir -p ~/hello-zig-demo/greeter
cd ~/hello-zig-demo/greeter
zig init
ls -Rzig init writes build.zig (how to build), build.zig.zon (the project's name, version and dependencies), src/main.zig (the program) and src/root.zig (a library module with a test). The project takes its name from the folder, so use a folder name made of letters, digits and underscores.
Replace src/main.zig with a program that takes a number from the command line and greets that many times:
cat > src/main.zig <<'ZIG'
const std = @import("std");
fn parseCount(text: []const u8) !u8 {
return std.fmt.parseInt(u8, text, 10);
}
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
const text = if (args.len > 1) args[1] else "3";
const count = parseCount(text) catch |err| {
std.debug.print("'{s}' is not a whole number from 0 to 255 ({s})\n", .{ text, @errorName(err) });
std.process.exit(1);
};
var buffer: [256]u8 = undefined;
var stdout_writer: std.Io.File.Writer = .init(.stdout(), init.io, &buffer);
const stdout = &stdout_writer.interface;
for (0..count) |i| {
try stdout.print("Hello number {d}\n", .{i + 1});
}
try stdout.flush();
}
ZIGThe new parts:
fn parseCount(text: []const u8) !u8takes a slice of bytes (Zig's string type is a slice ofu8) and returns either au8or an error. The!makes the return type an error union: the caller gets one or the other and has to deal with both.std.fmt.parseInt(u8, text, 10)turns text into a number in base 10. It returnserror.InvalidCharacterfor text such asabc, anderror.Overflowfor a number too big for au8, such as300.init.minimal.args.toSlice(init.arena.allocator())reads the command-line arguments into a list. Building that list needs memory, so you hand it an allocator: here the arena thatinitprovides, which is freed when the program exits.args[0]is the program's own name, so the first argument you type isargs[1].parseCount(text) catch |err| { ... }handles the error case. If parsing fails, the block runs with the error inerr, prints a message to standard error withstd.debug.print, and exits with status 1.@errorName(err)turns the error into its name as text.for (0..count) |i|loops from 0 up to, but not including,count, withias the current number.
Build and run it. zig build run builds the project and runs it; anything after -- goes to your program:
zig build run
zig build run -- 2
zig build run -- abc || echo "exit code: $?"
zig build
ls zig-out/binCheck it worked
zig build run prints Hello number 1 to Hello number 3. With 2 it stops at Hello number 2. With abc it prints 'abc' is not a whole number from 0 to 255 (InvalidCharacter), and the shell then shows a non-zero exit code. Try 300 and the message ends in (Overflow). ls zig-out/bin shows greeter: zig build installs the finished program there.
Step 6 · Compile C with zig cc, for Linux and Windows
Write the classic C Hello World next to your Zig file:
cd ~/hello-zig-demo
cat > hello.c <<'C'
#include <stdio.h>
int main(void)
{
printf("Hello from C, built by zig cc\n");
return 0;
}
C
zig cc -o hello-c hello.c
./hello-czig cc takes the same options as GCC and Clang, because underneath it is Clang, shipped inside Zig along with the C library headers for many systems. You did not install GCC, build-essential or any C headers for this.
Now build the same file for 64-bit Windows, without leaving Linux:
zig cc -target x86_64-windows-gnu -o hello.exe hello.c
file hello.exe-target names the processor, operating system and C library to build for. Setting up a cross-compiler for Windows with GCC usually means installing a separate MinGW toolchain; with Zig it is one flag. This is why projects use zig cc as their C toolchain even when they write no Zig at all, and why tools such as cargo-zigbuild exist to use it for Rust. Zig code cross-compiles the same way: zig build-exe -target x86_64-windows hello.zig produces hello.exe.
If you build for people on older or low-cost Windows laptops, you can produce and test their .exe from a single Linux machine, with no Windows licence on the build side.
Check it worked
./hello-c prints Hello from C, built by zig cc. file hello.exe reports something like PE32+ executable ... x86-64, for MS Windows. Copy hello.exe to a Windows computer and run it in a terminal there: it prints the same line.
Step 7 · Recognise the errors beginners hit
Zig's compiler is strict on purpose, and several of its errors surprise people coming from other languages. Make each one deliberately so you recognise it.
An error ignored. Remove try from the print line in hello.zig:
cd ~/hello-zig-demo
sed 's/try stdout.print/stdout.print/' hello.zig > ignored.zig
zig run ignored.zigThe compiler stops with error: error union of type 'error{WriteFailed}!void' is ignored and a note: consider using 'try', 'catch', or 'if'. error{WriteFailed} is the set of errors print can return. A function that can fail returns an error union, and Zig does not let you drop it on the floor.
A variable that never changes. Write a tiny program that declares count with var but never changes it:
cat > mutable.zig <<'ZIG'
const std = @import("std");
pub fn main() void {
var count: u8 = 3;
std.debug.print("count is {d}\n", .{count});
}
ZIG
zig run mutable.zigYou get error: local variable is never mutated and the note consider using 'const'. Zig wants const whenever a value does not change, so readers can trust that var really means "this changes".
An unused value. Unused local variables are errors, not warnings. If you declare const name = "Ada"; and never use it, the compiler reports error: unused local constant. While experimenting, write _ = name; to tell the compiler you meant it.
Nothing printed. If you forget try stdout.flush();, the program compiles and runs but prints nothing, because the text is still sitting in the buffer. When output goes missing, check the flush first.
Old examples that no longer compile. Code that uses std.io.getStdOut().writer() was written for Zig 0.14 or earlier, and code with pub fn main() !void plus std.fs.File.stdout() is from 0.15. Check which Zig version an example targets before you copy it, and use the language reference for your version at ziglang.org/documentation/0.17.1.
Check it worked
You have seen error union of type ... is ignored and local variable is never mutated in your own terminal, and neither command produced a program.
Step 8 · Clean up
Delete the demo folder:
cd ~
rm -rf ~/hello-zig-demoKeep Zig if you plan to carry on. To remove it as well, delete ~/.local/bin/zig, the folder ~/.local/opt/zig-x86_64-linux-0.17.1 (or the aarch64 one), and Zig's cache in ~/.cache/zig.
Check it worked
ls ~/hello-zig-demo reports No such file or directory.
Next steps
Zig is used for the Bun JavaScript runtime, the TigerBeetle financial database and the Ghostty terminal, and as a drop-in C cross-compiler in build systems that never touch Zig code.
- See the C program and its compile stages in detail: Hello World in C.
- Compare Zig's explicit errors with another systems language that has no garbage collector: Hello World in Rust.
- Try another language that aims to improve on C: Hello World in D.
Related tutorials
- Hello World in x86-64 assembly with NASM and Linux system callsYou will write an x86-64 assembly program that prints a line using only Linux system calls, assemble it with NASM, link it with ld, check its exit status, then loop it three times and read its machine code with objdump.
- Hello World in WebAssembly text format with wabt and WasmtimeYou will write a WebAssembly module by hand in the text format, assemble it with wat2wasm, print Hello World through WASI in Wasmtime 50, and call an exported add function from both Wasmtime and Node.js.
- Hello World in TypeScript: catch a type error before it runsYou will install TypeScript 7 in a throwaway folder, compile and run a typed Hello World on Node.js 26, watch the compiler reject a wrong argument, and run the same file directly with Node's built-in type stripping.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials