conststd=@import("std");pubfnbuild(b:*std.Build)void{consttarget=b.standardTargetOptions(.{});constoptimize=b.standardOptimizeOption(.{});constexe=b.addExecutable(.{.name="test",.root_source_file=.{.path="src/main.zig"},.target=target,.optimize=optimize,});b.installArtifact(exe);construn_cmd=b.addRunArtifact(exe);run_cmd.step.dependOn(b.getInstallStep());if(b.args)|args|{run_cmd.addArgs(args);}construn_step=b.step("run","Run the app");run_step.dependOn(&run_cmd.step);constunit_tests=b.addTest(.{.root_source_file=.{.path="src/main.zig"},.target=target,.optimize=optimize,});construn_unit_tests=b.addRunArtifact(unit_tests);consttest_step=b.step("test","Run unit tests");test_step.dependOn(&run_unit_tests.step);}
$ zig build --help
使用方法: zig build [steps][options]
Steps:
install (default) Copy build artifacts to prefix path
uninstall Remove build artifacts from prefix path
step-name This is what is shown in helpGeneral Options:
...
Project-Specific Options:
-Dtarget=[string] The CPU architecture, OS, and ABI to build for
-Dcpu=[string] Target CPU features to add or subtract
-Doptimize=[enum] Prioritize performance, safety, or binary size (-O flag)
Supported Values:
Debug
ReleaseSafe
ReleaseFast
ReleaseSmall
为了开发用户体验和一般便利性,从构建脚本中直接运行程序是非常实用的。这通常是通过运行步骤实现的,可以通过 zig build run 调用。
为此,我们需要一个 RunStep,它将执行我们能在系统上运行的任何可执行文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
conststd=@import("std");pubfnbuild(b:*std.build.Builder)void{consttarget=b.standardTargetOptions(.{});constoptimize=b.standardOptimizeOption(.{});constexe=b.addExecutable(.{.name="fresh",.root_source_file=.{.path="src/main.zig"},.target=target,.optimize=optimize,});construn_cmd=b.addRunArtifact(exe);run_cmd.step.dependOn(b.getInstallStep());construn_step=b.step("run","Run the app");run_step.dependOn(&run_cmd.step);}
RunStep 有几个函数可以为执行进程的 argv 添加值:
addArg 将向 argv 添加一个字符串参数。
addArgs 将同时添加多个字符串参数
addArtifactArg 将向 argv 添加 LibExeObjStep 的结果文件
addFileSourceArg 会将其他步骤生成的任何文件添加到 argv。
请注意,第一个参数必须是我们要运行的可执行文件的路径。在本例中,我们要运行 exe 的编译输出。
现在,当我们调用 zig build run 时,我们将看到与自己运行已安装的 exe 相同的输出:
conststd=@import("std");pubfnbuild(b:*std.build.Builder)void{consttarget=b.standardTargetOptions(.{});constoptimize=b.standardOptimizeOption(.{});constexe=b.addExecutable(.{.name="fresh",.root_source_file=.{.path="src/main.zig"},.target=target,.optimize=optimize,});construn_cmd=b.addRunArtifact(exe);run_cmd.step.dependOn(b.getInstallStep());if(b.args)|args|{run_cmd.addArgs(args);}construn_step=b.step("run","Run the app");run_step.dependOn(&run_cmd.step);}