Skip to content

Use xmake to build Zig project

ruki edited this page Mar 5, 2021 · 6 revisions

It is recommended to use the zig 0.8.0-dev version to test the following examples.

Create an empty project

$ xmake create -l zig -t console test

xmake.lua content:

target("test")
     set_kind("binary")
     add_files("src/main.zig")

Build zig project

We only need run the following command:

$ xmake

Run built program

$ xmake run
hello zig!

Build with debug mode and load debugger

We need add mode.debug rule in xmake.lua first.

add_rules("mode.debug", "mode.release")
target("test")
     set_kind("binary")
     add_files("src/main.zig")

then we switch to debug mode and rebuild it.

$ xmake f -m debug
$ xmake

and we run target program and load lldb.

$ xmake -d
(lldb) target create "/Users/ruki/projects/personal/xmake/tests/projects/package/toolchai
n_zig/build/macosx/x86_64/debug/test"
Current executable set to '/Users/ruki/projects/personal/xmake/tests/projects/package/too
lchain_zig/build/macosx/x86_64/debug/test' (x86_64).
(lldb)

Pull zig toolchain automatically

We can download zig toolchain and use it to build zig project automatically if there is not zig on our machine.

add_requires("zig 0.7.x")

target("test")
    set_kind("binary")
    add_files("src/main.zig")
    set_toolchains("@zig")

then run

$ xmake
note: try installing these packages (pass -y to skip confirm)?
in xmake-repo:
  -> zig 0.7.1
please input: y (y/n)

  => download https://ziglang.org/download/0.7.1/zig-macos-x86_64-0.7.1.tar.xz .. ok
  => install zig 0.7.1 .. ok
[ 25%]: ccache compiling.release src/main.zig
[ 50%]: linking.release test
[100%]: build ok!

Build zig and c projects

target("demo")
    set_kind("binary")
    add_files("src/*.c")
    add_files("src/main.zig")

run

$ xmake

Use c/c++ 3rd packages in zig projects

add_requires("libcurl", "zlib 1.12.x")
target("demo")
    set_kind("binary")
    add_files("src/main.zig")
    add_packages("libcurl", "zlib")

Use zig cc to build c/c++ projects

We write a c++ project with xmake.lua first.

target("test")
    set_kind("binary")
    add_files("src/*.cpp")

then use xmake to switch to zig toolchain and build it.

$ xmake f --toolchain=zig
$ xmake

Use zig/xmake to do cross-compilation

We can build zig program for windows/x86 on macOS.

$ xmake f --toolchain=zig -p windows -a x86
$ xmake

View build verbose infomation

$ xmake -v
[ 25%]: ccache compiling.release src/main.zig
zig build-obj -target x86_64-macos-gnu -O ReleaseFast --cache-dir build/.objs/test/macosx/x86_64/release/zi
g-cache -femit-bin=build/.objs/test/macosx/x86_64/release/src/main.zig.o src/main.zig
[ 50%]: linking.release test
zig build-exe -target x86_64-macos-gnu --strip -femit-bin=build/macosx/x86_64/release/test build/.objs/test
/macosx/x86_64/release/src/main.zig.o
[100%]: build ok!

More examples

Clone this wiki locally