Skip to main content

Zig

tip
  • ARM < v7 很多不支持
  • self-hosted compiler #89
docker run --rm -it -v $PWD:/host -w /host wener/zig
hello.zig
const std = @import("std");

pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello, {s}!\n", .{"world"});
}
hello.zig
const print = @import("std").debug.print;

pub fn main() void {
print("Hello, world!\n", .{});
}
zig build-exe hello.zig
# 交叉编译
zig targets # 所有 targets
zig build-exe -target arm-linux hello.zig

zig build-exe -target arm-linux-musleabi -mcpu arm1176jzf_s hello.zig
zig build-exe -target arm-linux-gnueabi -mcpu arm1176jzf_s hello.zig

# hello 约 4.4k
zig build-exe --strip -O ReleaseSmall hello.zig
  • flags
    • -fsingle-threaded
    • -mcpu=arm926ej_s+soft_float
    • -l[lib], --library [lib] - 在需要时 link 系统库
    • -L[d], --library-directory [d] - 添加 库 目录

C Interop

  • --verbose-cc 查看 cc 命令
hello.c
#include <stdio.h>

int main(int argc, char **argv) {
printf("Hello world\n");
return 0;
}
# 直接编译 C
zig build-exe hello.c
ldd hello
file hello
# 静态链接
# x86_64-macos
# x86_64-macos-musl 失败
zig build-exe hello.c --library c -target x86_64-macos-gnu
# macOS 下交叉编译 - 静态链接 ~11k
zig build-exe hello.c --library c -target x86_64-linux-musl
file hello
  • 交叉编译第一次会慢 - 预编译一些内容