特性亮点
小巧而简单的语言
把精力放在调试应用上,而不是调试你对编程语言的理解。
Zig 的全部语法由一个 580 行的 PEG 语法文件规定。
Zig 没有隐式控制流,没有隐式内存分配,没有预处理器,也没有宏。如果一段 Zig 代码看起来不像是跳转去调用某个函数,那它就确实没有调用。这意味着你可以确定,下面的代码只会先调用 foo(),再调用 bar();即使不知道其中任何东西的类型,这一点也有保证:
var a = b + c.d;
foo();
bar();
隐式控制流的例子:
- D 有
@property函数。这类方法的调用写法看起来像访问字段,所以在上面的例子中,c.d可能会调用函数。 - C++、D 和 Rust 支持运算符重载,所以
+运算符可能会调用函数。 - C++、D 和 Go 有 throw/catch 异常,所以
foo()可能抛出异常,导致bar()不被调用。
Zig 让所有控制流都只通过语言关键字和函数调用来管理,以此促进代码的可维护性和可读性。
性能与安全:两者兼得
Zig 有四种构建模式,它们可以任意混合搭配,细化到作用域粒度。
| 参数 | Debug | ReleaseSafe | ReleaseFast | ReleaseSmall |
|---|---|---|---|---|
| 优化:提升速度,妨碍调试,增加编译时间 | 开启 | 开启 | 开启 | |
| 运行时安全检查:降低速度,增大体积,以崩溃代替未定义行为 | 开启 | 开启 |
无论使用哪种构建模式,整数溢出在编译时的表现如下:
test "integer overflow at compile time" {
const x: u8 = 255;
_ = x + 1;
}$ zig test 1-integer-overflow.zig
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/1-integer-overflow.zig:3:11: error: overflow of integer type 'u8' with value '256'
_ = x + 1;
~~^~~
在带安全检查的构建中,它在运行时的表现如下:
test "integer overflow at runtime" {
var x: u8 = 255;
x += 1;
}$ zig test 2-integer-overflow-runtime.zig
1/1 2-integer-overflow-runtime.test.integer overflow at runtime...thread 2642538 panic: integer overflow
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/2-integer-overflow-runtime.zig:3:7: 0x1254595 in test.integer overflow at runtime (2-integer-overflow-runtime.zig)
x += 1;
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/compiler/test_runner.zig:295:25: 0x1208421 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/compiler/test_runner.zig:74:28: 0x1207c02 in main (test_runner.zig)
return mainTerminal(init);
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:789:88: 0x120439f in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:248:5: 0x1203d81 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/.zig-cache/o/a1306e55ec88396a7c587c71a32128a2/test --seed=0xc225c36d
这些栈跟踪在所有目标上都可用,包括独立环境(freestanding)目标。
使用 Zig,可以依靠启用安全检查的构建模式,只在性能瓶颈处有选择地关闭安全检查。例如,前面的示例可以这样修改:
test "actually undefined behavior" {
@setRuntimeSafety(false);
var x: u8 = 255;
x += 1; // XXX undefined behavior!
}Zig 把非法行为当作一把锋利的工具,既用来预防 bug,也用来提升性能。
说到性能,Zig 比 C 更快。
- 所有 Zig 代码都位于同一个编译单元中,一起进行优化。
- 精心选择的非法行为。例如,在 Zig 中,有符号整数和无符号整数溢出都属于非法行为,而在 C 中只有有符号整数溢出是这样。这使 Zig 能进行 C 中无法进行的优化。
- Zig 直接提供了 SIMD 向量类型,让编写可移植的向量化代码变得容易。
- 标准库提供了哈希表和数组列表等基本数据结构;而在 C 中,人们往往为了省事而用链表。
- 除非交叉编译,否则默认启用 CPU 的高级特性。
Zig 与 C 竞争,而不是依赖 C
Zig 标准库可以与 libc 集成,但并不依赖 libc。下面是 Hello World:
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, world!\n", .{});
}$ zig build-exe 4-hello.zig
$ ./4-hello
Hello, world!
使用 -O ReleaseSmall 编译,去除调试符号,采用单线程模式,为 x86_64-linux 目标生成的静态可执行文件只有 9.8 KiB:
$ zig build-exe hello.zig -O ReleaseSmall -fstrip -fsingle-threaded
$ wc -c hello
9944 hello
$ ldd hello
not a dynamic executable
Windows 构建甚至更小,只有 4096 字节:
$ zig build-exe hello.zig -O ReleaseSmall -fstrip -fsingle-threaded -target x86_64-windows
$ wc -c hello.exe
4096 hello.exe
$ file hello.exe
hello.exe: PE32+ executable (console) x86-64, for MS Windows
顶层声明与顺序无关
全局变量等顶层声明与顺序无关,并且是惰性分析的。全局变量的初始值在编译时求值。
var y: i32 = add(10, x);
const x: i32 = add(12, 34);
test "global variables" {
assert(x == 46);
assert(y == 56);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
const std = @import("std");
const assert = std.debug.assert;$ zig test 5-global-variables.zig
1/1 5-global-variables.test.global variables...OK
All 1 tests passed.
用可选类型代替空指针
在其他编程语言中,空引用是许多运行时异常的根源,甚至被指责为计算机科学中最严重的错误。
普通的 Zig 指针不能为 null:
test "null @intToPtr" {
const foo: *i32 = @ptrFromInt(0x0);
_ = foo;
}$ zig test 6-null-to-ptr.zig
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/6-null-to-ptr.zig:2:35: error: pointer type '*i32' does not allow address zero
const foo: *i32 = @ptrFromInt(0x0);
^~~
不过,任何类型都可以通过加上前缀 ? 变成可选类型:
const std = @import("std");
const assert = std.debug.assert;
test "null @intToPtr" {
const ptr: ?*i32 = @ptrFromInt(0x0);
assert(ptr == null);
}$ zig test 7-optional-syntax.zig
1/1 7-optional-syntax.test.null @intToPtr...OK
All 1 tests passed.
要解包可选值,可以用 orelse 提供默认值:
// malloc prototype included for reference
extern fn malloc(size: size_t) ?*u8;
fn doAThing() ?*Foo {
const ptr = malloc(1234) orelse return null;
// ...
}另一种做法是使用 if:
fn doAThing(optional_foo: ?*Foo) void {
// do some stuff
if (optional_foo) |foo| {
doSomethingWithFoo(foo);
}
// do some stuff
}同样的语法也适用于 while:
const std = @import("std");
pub fn main() void {
const msg = "hello this is dog";
var it = std.mem.tokenizeAny(u8, msg, " ");
while (it.next()) |item| {
std.debug.print("{s}\n", .{item});
}
}$ zig build-exe 10-optional-while.zig
$ ./10-optional-while
hello
this
is
dog
手动内存管理
用 Zig 编写的库可以用在任何地方:
为此,Zig 程序员必须自己管理内存,并且必须处理内存分配失败。
Zig 标准库也是如此。任何需要分配内存的函数都接受一个分配器参数。因此,Zig 标准库甚至可以用于独立环境(freestanding)目标。
除了全新的错误处理方式,Zig 还提供 defer 和 errdefer,让所有资源管理(不只是内存)都简单且易于验证。
defer 的示例参见无需 FFI/绑定即可集成 C 库。下面是使用 errdefer 的示例:
const Device = struct {
name: []u8,
fn create(allocator: *Allocator, id: u32) !Device {
const device = try allocator.create(Device);
errdefer allocator.destroy(device);
device.name = try std.fmt.allocPrint(allocator, "Device(id={d})", id);
errdefer allocator.free(device.name);
if (id == 0) return error.ReservedDeviceId;
return device;
}
};全新的错误处理方式
错误是值,不能被忽略:
const std = @import("std");
pub fn main() void {
_ = std.fs.cwd().openFile("does_not_exist/foo.txt", .{});
}$ zig build-exe 12-errors-as-values.zig
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/12-errors-as-values.zig:4:15: error: root source file struct 'fs' has no member named 'cwd'
_ = std.fs.cwd().openFile("does_not_exist/foo.txt", .{});
~~~~~~^~~~
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/fs.zig:1:1: note: struct declared here
//! File System.
^~~~~~~~~~~~~~~~
referenced by:
callMain [inlined]: /home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:788:64
callMainWithArgs [inlined]: /home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:729:20
posixCallMainAndExit: /home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:681:38
2 reference(s) hidden; use '-freference-trace=5' to see all references
可以用 catch 处理错误:
const std = @import("std");
const Io = std.Io;
pub fn main(init: std.process.Init) void {
const io = init.io;
const file: Io.File = Io.Dir.cwd().openFile(io, "does_not_exist/foo.txt", .{}) catch |err| label: {
std.debug.print("unable to open file: {}\n", .{err});
break :label .stderr();
};
var file_writer = file.writer(io, &.{});
file_writer.interface.writeAll("all your codebase are belong to us\n") catch return;
}$ zig build-exe 13-errors-catch.zig
$ ./13-errors-catch
unable to open file: error.FileNotFound
all your codebase are belong to us
关键字 try 是 catch |err| return err 的简写:
const std = @import("std");
const Io = std.Io;
pub fn main(init: std.process.Init) !void {
const io = init.io;
const file = try Io.Dir.cwd().openFile(io, "does_not_exist/foo.txt", .{});
defer file.close(io);
var file_writer = file.writer(io, &.{});
try file_writer.interface.writeAll("all your codebase are belong to us\n");
}$ zig build-exe 14-errors-try.zig
$ ./14-errors-try
error: FileNotFound
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/Io/Threaded.zig:4993:35: 0x11a0fa4 in dirOpenFilePosix (std.zig)
.NOENT => return error.FileNotFound,
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/Io/Dir.zig:581:5: 0x10374a0 in openFile (std.zig)
return io.vtable.dirOpenFile(io.userdata, dir, sub_path, options);
^
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/14-errors-try.zig:7:18: 0x11e87f8 in main (14-errors-try.zig)
const file = try Io.Dir.cwd().openFile(io, "does_not_exist/foo.txt", .{});
^
注意,这是错误返回追踪,而不是栈跟踪。代码没有为了得到这条追踪而付出展开栈的代价。
对错误使用 switch 关键字,可以确保处理所有可能的错误:
const std = @import("std");
test "switch on error" {
_ = parseInt("hi", 10) catch |err| switch (err) {};
}
fn parseInt(buf: []const u8, radix: u8) !u64 {
var x: u64 = 0;
for (buf) |c| {
const digit = try charToDigit(c);
if (digit >= radix) {
return error.DigitExceedsRadix;
}
x = try std.math.mul(u64, x, radix);
x = try std.math.add(u64, x, digit);
}
return x;
}
fn charToDigit(c: u8) !u8 {
const value = switch (c) {
'0'...'9' => c - '0',
'A'...'Z' => c - 'A' + 10,
'a'...'z' => c - 'a' + 10,
else => return error.InvalidCharacter,
};
return value;
}$ zig test 15-errors-switch.zig
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/15-errors-switch.zig:4:40: error: switch must handle all possibilities
_ = parseInt("hi", 10) catch |err| switch (err) {};
^~~~~~~~~~~~~~~
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/15-errors-switch.zig:4:40: note: unhandled error value: 'error.Overflow'
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/15-errors-switch.zig:4:40: note: unhandled error value: 'error.InvalidCharacter'
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/15-errors-switch.zig:4:40: note: unhandled error value: 'error.DigitExceedsRadix'
关键字 unreachable 用于断言不会发生错误:
const std = @import("std");
const Io = std.Io;
pub fn main(init: std.process.Init) void {
const io = init.io;
const file = Io.Dir.cwd().openFile(io, "does_not_exist/foo.txt", .{}) catch unreachable;
defer file.close(io);
var file_writer = file.writer(io, &.{});
file_writer.interface.writeAll("all your codebase are belong to us\n") catch unreachable;
}$ zig build-exe 16-unreachable.zig
$ ./16-unreachable
thread 2641205 panic: attempt to unwrap error: FileNotFound
error return context:
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/Io/Threaded.zig:4993:35: 0x11a0fa4 in dirOpenFilePosix (std.zig)
.NOENT => return error.FileNotFound,
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/Io/Dir.zig:581:5: 0x10374a0 in openFile (std.zig)
return io.vtable.dirOpenFile(io.userdata, dir, sub_path, options);
^
stack trace:
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/16-unreachable.zig:7:81: 0x11f2e21 in main (16-unreachable.zig)
const file = Io.Dir.cwd().openFile(io, "does_not_exist/foo.txt", .{}) catch unreachable;
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:827:30: 0x11e904d in callMain (std.zig)
return wrapMain(root.main(.{
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:248:5: 0x11e86e1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
在不安全的构建模式下,这会引发未定义行为,所以只应在确定一定成功时使用。
所有目标上都有栈跟踪
本页展示的栈跟踪和错误返回追踪适用于所有 Tier 1 支持的目标和部分 Tier 2 支持的目标。甚至包括独立环境目标!
此外,标准库可以在任意位置捕获栈跟踪,之后再将其输出到标准错误:
const std = @import("std");
var address_buffer: [8]usize = undefined;
var trace1: std.debug.StackTrace = .{
.return_addresses = address_buffer[0..4],
.skipped = .none,
};
var trace2: std.debug.StackTrace = .{
.return_addresses = address_buffer[4..],
.skipped = .none,
};
pub fn main() void {
foo();
bar();
std.debug.print("first one:\n", .{});
std.debug.dumpStackTrace(&trace1);
std.debug.print("\n\nsecond one:\n", .{});
std.debug.dumpStackTrace(&trace2);
}
fn foo() void {
trace1 = std.debug.captureCurrentStackTrace(.{}, address_buffer[0..4]);
}
fn bar() void {
trace2 = std.debug.captureCurrentStackTrace(.{}, address_buffer[4..]);
}$ zig build-exe 17-stack-traces.zig
$ ./17-stack-traces
first one:
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/17-stack-traces.zig:26:48: 0x11ea96f in foo (17-stack-traces.zig)
trace1 = std.debug.captureCurrentStackTrace(.{}, address_buffer[0..4]);
^
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/17-stack-traces.zig:16:8: 0x11e937c in main (17-stack-traces.zig)
foo();
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:788:64: 0x11e8cab in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:248:5: 0x11e86e1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(additional stack frames may have been skipped...)
second one:
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/17-stack-traces.zig:30:48: 0x11e9b4f in bar (17-stack-traces.zig)
trace2 = std.debug.captureCurrentStackTrace(.{}, address_buffer[4..]);
^
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/17-stack-traces.zig:17:8: 0x11e9381 in main (17-stack-traces.zig)
bar();
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:788:64: 0x11e8cab in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/start.zig:248:5: 0x11e86e1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(additional stack frames may have been skipped...)
标准库的 DebugAllocator 就使用这种技术报告内存泄漏和重复释放。
泛型数据结构与函数
类型是值,且必须在编译时已知:
const std = @import("std");
const assert = std.debug.assert;
test "types are values" {
const T1 = u8;
const T2 = bool;
assert(T1 != T2);
const x: T2 = true;
assert(x);
}$ zig test 18-types.zig
1/1 18-types.test.types are values...OK
All 1 tests passed.
泛型数据结构就是一个返回 type 的函数:
const std = @import("std");
fn List(comptime T: type) type {
return struct {
items: []T,
len: usize,
};
}
pub fn main() void {
var buffer: [10]i32 = undefined;
var list: List(i32) = .{
.items = &buffer,
.len = 0,
};
list.items[0] = 1234;
list.len += 1;
std.debug.print("{d}\n", .{list.items.len});
}$ zig build-exe 19-generics.zig
$ ./19-generics
10
编译时反射与编译时代码执行
内置函数 @typeInfo 提供反射功能:
const std = @import("std");
const Header = struct {
magic: u32,
name: []const u8,
};
pub fn main() void {
printInfoAboutStruct(Header);
}
fn printInfoAboutStruct(comptime T: type) void {
const info = @typeInfo(T).@"struct";
inline for (info.field_types, info.field_names) |FieldType, field_name| {
std.debug.print(
"{s} has a field called {s} with type {s}\n",
.{
@typeName(T),
field_name,
@typeName(FieldType),
},
);
}
}$ zig build-exe 20-reflection.zig
$ ./20-reflection
20-reflection.Header has a field called magic with type u32
20-reflection.Header has a field called name with type []const u8
Zig 标准库用这种技术实现格式化输出。尽管 Zig 是一门小巧而简单的语言,它的格式化输出却完全用 Zig 实现。相比之下,C 中 printf 的编译错误是硬编码在编译器里的。同样,Rust 的格式化输出宏也是硬编码在编译器里的。
Zig 还可以在编译时对函数和代码块求值。在某些上下文中(例如全局变量的初始化),表达式会隐式地在编译时求值。在其他情况下,可以用 comptime 关键字显式地在编译时对代码求值。与断言结合使用时,这一点尤其强大:
const std = @import("std");
const assert = std.debug.assert;
fn fibonacci(x: u32) u32 {
if (x <= 1) return x;
return fibonacci(x - 1) + fibonacci(x - 2);
}
test "compile-time evaluation" {
var array: [fibonacci(6)]i32 = undefined;
@memset(&array, 42);
comptime {
assert(array.len == 12345);
}
}$ zig test 21-comptime.zig
/home/ci/deps/zig-x86_64-linux-0.17.0/lib/std/debug.zig:442:14: error: reached unreachable code
if (!ok) unreachable; // assertion failure
^~~~~~~~~~~
/home/ci/.cache/act/801ef91cb8f01710/hostexecutor/zig-code/features/21-comptime.zig:15:15: note: called at comptime here
assert(array.len == 12345);
~~~~~~^~~~~~~~~~~~~~~~~~~~
无需 FFI/绑定即可集成 C 库
@cImport 可以直接导入类型、变量、函数和简单的宏,供 Zig 使用。它甚至能把 C 的内联函数翻译成 Zig。
下面是使用 libsoundio 输出正弦波的示例:
const c = @cImport(@cInclude("soundio/soundio.h"));
const std = @import("std");
fn sio_err(err: c_int) !void {
switch (err) {
c.SoundIoErrorNone => {},
c.SoundIoErrorNoMem => return error.NoMem,
c.SoundIoErrorInitAudioBackend => return error.InitAudioBackend,
c.SoundIoErrorSystemResources => return error.SystemResources,
c.SoundIoErrorOpeningDevice => return error.OpeningDevice,
c.SoundIoErrorNoSuchDevice => return error.NoSuchDevice,
c.SoundIoErrorInvalid => return error.Invalid,
c.SoundIoErrorBackendUnavailable => return error.BackendUnavailable,
c.SoundIoErrorStreaming => return error.Streaming,
c.SoundIoErrorIncompatibleDevice => return error.IncompatibleDevice,
c.SoundIoErrorNoSuchClient => return error.NoSuchClient,
c.SoundIoErrorIncompatibleBackend => return error.IncompatibleBackend,
c.SoundIoErrorBackendDisconnected => return error.BackendDisconnected,
c.SoundIoErrorInterrupted => return error.Interrupted,
c.SoundIoErrorUnderflow => return error.Underflow,
c.SoundIoErrorEncodingString => return error.EncodingString,
else => return error.Unknown,
}
}
var seconds_offset: f32 = 0;
fn write_callback(
maybe_outstream: ?[*]c.SoundIoOutStream,
frame_count_min: c_int,
frame_count_max: c_int,
) callconv(.C) void {
_ = frame_count_min;
const outstream: *c.SoundIoOutStream = &maybe_outstream.?[0];
const layout = &outstream.layout;
const float_sample_rate: f32 = @floatFromInt(outstream.sample_rate);
const seconds_per_frame = 1.0 / float_sample_rate;
var frames_left = frame_count_max;
while (frames_left > 0) {
var frame_count = frames_left;
var areas: [*]c.SoundIoChannelArea = undefined;
sio_err(c.soundio_outstream_begin_write(
maybe_outstream,
@ptrCast(&areas),
&frame_count,
)) catch |err| std.debug.panic("write failed: {s}", .{@errorName(err)});
if (frame_count == 0) break;
const pitch = 440.0;
const radians_per_second = pitch * 2.0 * std.math.pi;
var frame: c_int = 0;
while (frame < frame_count) : (frame += 1) {
const float_frame: f32 = @floatFromInt(frame);
const sample = std.math.sin((seconds_offset + float_frame *
seconds_per_frame) * radians_per_second);
{
var channel: usize = 0;
while (channel < @as(usize, @intCast(layout.channel_count))) : (channel += 1) {
const channel_ptr = areas[channel].ptr;
const sample_ptr: *f32 = @ptrCast(@alignCast(&channel_ptr[@intCast(areas[channel].step * frame)]));
sample_ptr.* = sample;
}
}
}
const float_frame_count: f32 = @floatFromInt(frame_count);
seconds_offset += seconds_per_frame * float_frame_count;
sio_err(c.soundio_outstream_end_write(maybe_outstream)) catch |err| std.debug.panic("end write failed: {s}", .{@errorName(err)});
frames_left -= frame_count;
}
}
pub fn main() !void {
const soundio = c.soundio_create();
defer c.soundio_destroy(soundio);
try sio_err(c.soundio_connect(soundio));
c.soundio_flush_events(soundio);
const default_output_index = c.soundio_default_output_device_index(soundio);
if (default_output_index < 0) return error.NoOutputDeviceFound;
const device = c.soundio_get_output_device(soundio, default_output_index) orelse return error.OutOfMemory;
defer c.soundio_device_unref(device);
std.debug.print("Output device: {s}\n", .{device.*.name});
const outstream = c.soundio_outstream_create(device) orelse return error.OutOfMemory;
defer c.soundio_outstream_destroy(outstream);
outstream.*.format = c.SoundIoFormatFloat32NE;
outstream.*.write_callback = write_callback;
try sio_err(c.soundio_outstream_open(outstream));
try sio_err(c.soundio_outstream_start(outstream));
while (true) c.soundio_wait_events(soundio);
}$ zig build-exe sine.zig -lsoundio -lc
$ ./sine
Output device: Built-in Audio Analog Stereo
^C
这段 Zig 代码比等效的 C 代码简单得多,还具备更多的安全保护。这一切都是通过直接导入 C 头文件实现的,无需任何 API 绑定。
在使用 C 库这件事上,Zig 比 C 自己做得更好。
Zig 也是 C 编译器
下面是用 Zig 构建 C 代码的示例:
hello.c#include <stdio.h>
int main(int argc, char **argv) {
printf("Hello world\n");
return 0;
}
$ zig build-exe hello.c -lc
$ ./hello
Hello world
可以用 --verbose-cc 查看这次执行了哪条 C 编译器命令:
$ zig build-exe hello.c -lc --verbose-cc
zig cc -MD -MV -MF .zig-cache/tmp/42zL6fBH8fSo-hello.o.d -nostdinc -fno-spell-checking -isystem /home/andy/dev/zig/build/lib/zig/include -isystem /home/andy/dev/zig/build/lib/zig/libc/include/x86_64-linux-gnu -isystem /home/andy/dev/zig/build/lib/zig/libc/include/generic-glibc -isystem /home/andy/dev/zig/build/lib/zig/libc/include/x86_64-linux-any -isystem /home/andy/dev/zig/build/lib/zig/libc/include/any-linux-any -march=native -g -fstack-protector-strong --param ssp-buffer-size=4 -fno-omit-frame-pointer -o .zig-cache/tmp/42zL6fBH8fSo-hello.o -c hello.c -fPIC
注意,如果再运行一次这条命令,不会有任何输出,而且会立即完成:
$ time zig build-exe hello.c -lc --verbose-cc
real 0m0.027s
user 0m0.018s
sys 0m0.009s
这要归功于构建产物缓存。Zig 会自动解析 .d 文件,借助可靠的缓存系统避免重复工作。
Zig 不仅能编译 C 代码,而且有一个非常好的理由让人把 Zig 当作 C 编译器使用:Zig 自带 libc。
导出函数、变量和类型,供 C 代码依赖
Zig 的主要用途之一,是导出符合 C ABI 的库,供其他编程语言调用。在函数、变量和类型前加上 export 关键字,它们就会成为库 API 的一部分:
export fn add(a: i32, b: i32) i32 {
return a + b;
}生成静态库:
$ zig build-lib mathtest.zig
生成动态库:
$ zig build-lib mathtest.zig -dynamic
下面是使用 Zig 构建系统的示例:
test.c#include "mathtest.h"
#include <stdio.h>
int main(int argc, char **argv) {
int32_t result = add(42, 1337);
printf("%d\n", result);
return 0;
}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));
const exe = b.addExecutable("test", null);
exe.addCSourceFile("test.c", &[_][]const u8{"-std=c99"});
exe.linkLibrary(lib);
exe.linkSystemLibrary("c");
b.default_step.dependOn(&exe.step);
const run_cmd = exe.run();
const test_step = b.step("test", "Test the program");
test_step.dependOn(&run_cmd.step);
}$ zig build test
1379
交叉编译是一等用例
Zig 为所有受支持的目标构建,都与宿主机无关。不需要单独的“交叉工具链”之类的东西。下面是一个本机的 Hello World:
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, world!\n", .{});
}$ zig build-exe 4-hello.zig
$ ./4-hello
Hello, world!
现在为 x86_64-windows、x86_64-macos 和 aarch64-linux 构建它:
$ zig build-exe hello.zig -target x86_64-windows
$ file hello.exe
hello.exe: PE32+ executable (console) x86-64, for MS Windows
$ zig build-exe hello.zig -target x86_64-macos
$ file hello
hello: Mach-O 64-bit x86_64 executable, flags:<NOUNDEFS|DYLDLINK|TWOLEVEL|PIE>
$ zig build-exe hello.zig -target aarch64-linux
$ file hello
hello: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, with debug_info, not stripped
这在任何 Tier 3 及以上的目标上都可行,并且可以面向任何 Tier 3 及以上的目标。
Zig 自带 libc
可以用 zig targets 查看可用的 libc 目标:
...
.libc = .{
"arc-linux-gnu",
"arm-freebsd-eabihf",
"arm-linux-gnueabi",
"arm-linux-gnueabihf",
"arm-linux-musleabi",
"arm-linux-musleabihf",
"arm-netbsd-eabi",
"arm-netbsd-eabihf",
"armeb-linux-gnueabi",
"armeb-linux-gnueabihf",
"armeb-linux-musleabi",
"armeb-linux-musleabihf",
"armeb-netbsd-eabi",
"armeb-netbsd-eabihf",
"thumb-linux-musleabi",
"thumb-linux-musleabihf",
"thumb-windows-gnu",
"thumbeb-linux-musleabi",
"thumbeb-linux-musleabihf",
"aarch64-freebsd-none",
"aarch64-linux-gnu",
"aarch64-linux-musl",
"aarch64-maccatalyst-none",
"aarch64-macos-none",
"aarch64-netbsd-none",
"aarch64-windows-gnu",
"aarch64_be-linux-gnu",
"aarch64_be-linux-musl",
"aarch64_be-netbsd-none",
"csky-linux-gnueabi",
"csky-linux-gnueabihf",
"hexagon-linux-musl",
"loongarch64-linux-gnu",
"loongarch64-linux-gnusf",
"loongarch64-linux-musl",
"loongarch64-linux-muslsf",
"m68k-linux-gnu",
"m68k-linux-musl",
"m68k-netbsd-none",
"mips-linux-gnueabi",
"mips-linux-gnueabihf",
"mips-linux-musleabi",
"mips-linux-musleabihf",
"mips-netbsd-eabi",
"mips-netbsd-eabihf",
"mipsel-linux-gnueabi",
"mipsel-linux-gnueabihf",
"mipsel-linux-musleabi",
"mipsel-linux-musleabihf",
"mipsel-netbsd-eabi",
"mipsel-netbsd-eabihf",
"mips64-linux-gnuabi64",
"mips64-linux-gnuabin32",
"mips64-linux-muslabi64",
"mips64-linux-muslabin32",
"mips64el-linux-gnuabi64",
"mips64el-linux-gnuabin32",
"mips64el-linux-muslabi64",
"mips64el-linux-muslabin32",
"powerpc-linux-gnueabi",
"powerpc-linux-gnueabihf",
"powerpc-linux-musleabi",
"powerpc-linux-musleabihf",
"powerpc-netbsd-eabi",
"powerpc-netbsd-eabihf",
"powerpc64-freebsd-none",
"powerpc64-linux-gnu",
"powerpc64-linux-musl",
"powerpc64le-freebsd-none",
"powerpc64le-linux-gnu",
"powerpc64le-linux-musl",
"riscv32-linux-gnu",
"riscv32-linux-musl",
"riscv64-freebsd-none",
"riscv64-linux-gnu",
"riscv64-linux-musl",
"s390x-linux-gnu",
"s390x-linux-musl",
"sparc-linux-gnu",
"sparc-netbsd-none",
"sparc64-linux-gnu",
"sparc64-netbsd-none",
"wasm32-wasi-musl",
"x86-freebsd-none",
"x86-linux-gnu",
"x86-linux-musl",
"x86-netbsd-none",
"x86-windows-gnu",
"x86_64-freebsd-none",
"x86_64-linux-gnu",
"x86_64-linux-gnux32",
"x86_64-linux-musl",
"x86_64-linux-muslx32",
"x86_64-maccatalyst-none",
"x86_64-macos-none",
"x86_64-netbsd-none",
"x86_64-windows-gnu",
},
...
这意味着,针对这些目标的 -lc 不依赖任何系统文件!
再来看一下那个 C 语言 hello world 示例:
$ zig build-exe hello.c -lc
$ ./hello
Hello world
$ ldd ./hello
linux-vdso.so.1 (0x00007ffd03dc9000)
libc.so.6 => /lib/libc.so.6 (0x00007fc4b62be000)
libm.so.6 => /lib/libm.so.6 (0x00007fc4b5f29000)
libpthread.so.0 => /lib/libpthread.so.0 (0x00007fc4b5d0a000)
libdl.so.2 => /lib/libdl.so.2 (0x00007fc4b5b06000)
librt.so.1 => /lib/librt.so.1 (0x00007fc4b58fe000)
/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc4b6672000)
$ zig build-exe hello.c -lc -target x86_64-linux-musl
$ ./hello
Hello world
$ ldd hello
not a dynamic executable
在这个示例中,Zig 从源码构建了 musl libc,然后与之链接。得益于缓存系统,为 x86_64-linux 构建的 musl libc 会一直保留,之后再需要这个 libc 时可以立即使用。
这意味着这项功能在任何平台上都可用。Windows 和 macOS 用户可以为上面列出的任意目标构建 Zig 和 C 代码,并链接 libc。同样,代码也可以交叉编译到其他架构:
$ zig build-exe hello.c -lc -target aarch64-linux-gnu
$ file hello
hello: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-aarch64.so.1, for GNU/Linux 2.0.0, with debug_info, not stripped
Zig 是比 C 编译器更好的 C 编译器!
这项功能不只是把一套交叉编译工具链和 Zig 打包在一起。例如,Zig 附带的 libc 头文件未压缩时总共 130 MiB。而仅 x86_64 上的 musl libc 加 linux 头文件就有 8 MiB,glibc 的头文件有 3.1 MiB(glibc 不含 linux 头文件),而 Zig 目前附带了 97 个 libc。如果简单地打包在一起,总大小会达到 776 MiB。不过,借助这个 process_headers 工具和一些老派的手工劳动,Zig 的二进制压缩包总共仍然只有大约 50 MiB;而它支持所有这些目标的 libc,还包含 compiler-rt、libunwind、libcxx 和 libtsan,同时还是一个与 clang 兼容的 C 编译器。作为对比,llvm.org 提供的 clang 8.0.0 本身的 Windows 二进制构建就有 132 MiB。
Zig 构建系统与包管理器
Zig 自带构建系统,所以不需要再用单独的工具来编排构建过程。
$ zig init
info: created build.zig
info: created build.zig.zon
info: created src/main.zig
info: created src/root.zig
info: see `zig build --help` for a menu of options
const std = @import("std");
pub fn main() !void {
std.debug.print("All your base are belong to us.\n", .{});
}const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("example", "src/main.zig");
exe.setBuildMode(mode);
const run_cmd = exe.run();
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
b.default_step.dependOn(&exe.step);
b.installArtifact(exe);
}来看看那个 --help 菜单。
$ zig build --help
Usage: zig build [steps] [options]
Steps:
install (default) Copy build artifacts to prefix path
uninstall Remove build artifacts from prefix path
run Run the app
test Run tests
Project-Specific Options:
-Dtarget=[string] The CPU architecture, OS, and ABI to build for
-Dcpu=[string] Target CPU features to add or subtract
-Dofmt=[string] Target object format
-Ddynamic-linker=[string] Path to interpreter on the target system
-Doptimize=[enum] Prioritize performance, safety, or binary size
Supported Values:
Debug
ReleaseSafe
ReleaseFast
ReleaseSmall
System Integration Options:
--search-prefix [path] Add a path to look for binaries, libraries, headers
--sysroot [path] Set the system root directory (usually /)
--libc [file] Provide a file which specifies libc paths
--system [pkgdir] Disable package fetching; enable all integrations
-fsys=[name] Enable a system integration
-fno-sys=[name] Disable a system integration
Available System Integrations: Enabled:
(none) -
General Options:
-p, --prefix [path] Where to install files (default: zig-out)
--prefix-lib-dir [path] Where to install libraries
--prefix-exe-dir [path] Where to install executables
--prefix-include-dir [path] Where to install C header files
--release[=mode] Request release mode, optionally specifying a
preferred optimization mode: fast, safe, small
-fdarling, -fno-darling Integration with system-installed Darling to
execute macOS programs on Linux hosts
(default: no)
-fqemu, -fno-qemu Integration with system-installed QEMU to execute
foreign-architecture programs on Linux hosts
(default: no)
--libc-runtimes [path] Enhances QEMU integration by providing dynamic libc
(e.g. glibc or musl) built for multiple foreign
architectures, allowing execution of non-native
programs that link with libc.
-frosetta, -fno-rosetta Rely on Rosetta to execute x86_64 programs on
ARM64 macOS hosts. (default: no)
-fwasmtime, -fno-wasmtime Integration with system-installed wasmtime to
execute WASI binaries. (default: no)
-fwine, -fno-wine Integration with system-installed Wine to execute
Windows programs on Linux hosts. (default: no)
-h, --help Print this help and exit
-l, --list-steps Print available steps
--verbose Print commands before executing them
--color [auto|off|on] Enable or disable colored error messages
--error-style [style] Control how build errors are printed
verbose (Default) Report errors with full context
minimal Report errors after summary, excluding context like command lines
verbose_clear Like 'verbose', but clear the terminal at the start of each update
minimal_clear Like 'minimal', but clear the terminal at the start of each update
--multiline-errors [style] Control how multi-line error messages are printed
indent (Default) Indent non-initial lines to align with initial line
newline Include a leading newline so that the error message is on its own lines
none Print as usual so the first line is misaligned
--summary [mode] Control the printing of the build summary
all Print the build summary in its entirety
new Omit cached steps
failures (Default if short-lived) Only print failed steps
line (Default if long-lived) Only print the single-line summary
none Do not print the build summary
-j<N> Limit concurrent jobs (default is to use all CPU cores)
--maxrss <bytes> Limit memory usage (default is to use available memory)
--skip-oom-steps Instead of failing, skip steps that would exceed --maxrss
--test-timeout <timeout> Limit execution time of unit tests, terminating if exceeded.
The timeout must include a unit: ns, us, ms, s, m, h
--fetch[=mode] Fetch dependency tree (optionally choose laziness) and exit
needed (Default) Lazy dependencies are fetched as needed
all Lazy dependencies are always fetched
--watch Continuously rebuild when source files are modified
--debounce <ms> Delay before rebuilding after changed file detected
--webui[=ip] Enable the web interface on the given IP address
--fuzz[=limit] Continuously search for unit test failures with an optional
limit to the max number of iterations. The argument supports
an optional 'K', 'M', or 'G' suffix (e.g. '10K'). Implies
'--webui' when no limit is specified.
--time-report Force full rebuild and provide detailed information on
compilation time of Zig source code (implies '--webui')
-fincremental Enable incremental compilation
-fno-incremental Disable incremental compilation
Advanced Options:
-freference-trace[=num] How many lines of reference trace should be shown per compile error
-fno-reference-trace Disable reference trace
-fallow-so-scripts Allows .so files to be GNU ld scripts
-fno-allow-so-scripts (default) .so files must be ELF files
--build-file [file] Override path to build.zig
--cache-dir [path] Override path to local Zig cache directory
--global-cache-dir [path] Override path to global Zig cache directory
--zig-lib-dir [arg] Override path to Zig lib directory
--build-runner [file] Override path to build runner
--seed [integer] For shuffling dependency traversal order (default: random)
--build-id[=style] At a minor link-time expense, embeds a build ID in binaries
fast 8-byte non-cryptographic hash (COFF, ELF, WASM)
sha1, tree 20-byte cryptographic hash (ELF, WASM)
md5 16-byte cryptographic hash (ELF)
uuid 16-byte random UUID (ELF, WASM)
0x[hexstring] Constant ID, maximum 32 bytes (ELF, WASM)
none (default) No build ID
--debug-log [scope] Enable debugging the compiler
--debug-pkg-config Fail if unknown pkg-config flags encountered
--debug-rt Debug compiler runtime libraries
--verbose-link Enable compiler debug output for linking
--verbose-air Enable compiler debug output for Zig AIR
--verbose-llvm-ir[=file] Enable compiler debug output for LLVM IR
--verbose-llvm-bc=[file] Enable compiler debug output for LLVM BC
--verbose-cimport Enable compiler debug output for C imports
--verbose-cc Enable compiler debug output for C compilation
--verbose-llvm-cpu-features Enable compiler debug output for LLVM CPU features
可以看到,可用的步骤之一是 run。
$ zig build run
All your codebase are belong to us.
Run `zig build test` to run the tests.
下面是一些构建脚本示例:
支持多种多样的目标
Zig 用“支持等级”体系来说明对不同目标的支持程度。
对软件包维护者友好
虽然 Zig 是自托管的,但得益于基于 WebAssembly 的自举过程,从源码构建只依赖系统的 C/C++ 工具链和 LLVM,使用标准的 CMake 构建步骤即可。
对于希望避免二进制文件的发行版,有一套文档完备的步骤,可以在不使用任何二进制文件的情况下重现 Zig。
我们希望将来能激励第三方用 C 实现一个 Zig 解释器,把这一过程缩减为 O(1) 步。
构建系统明确把系统集成当作一种意图。例如,--system <path> 标志会禁用包获取,并启用所有 -fsys=[name] 选项。这些“系统集成选项”可以在构建脚本中使用,让软件包维护者和上游开发者能够相互配合:软件包维护者需要的补丁更少,上游作者也可以针对系统集成的构建配置作出有意识的选择。
非 Debug 的构建模式是可重现的(确定性的)。
有一个 JSON 版本的下载页面。