Zig-trycompile

zig-trycompile:


Have you ever used another build system?
Then you have probably ran across something like cmake’s trycompile, meson’s compiler.compiles, autoconf’s AC_COMPILE_IFELSE or similar.

Now Zig doesn’t have to be unique : https://codeberg.org/Jan200101/zig_trycompile

By (ab)using pre-0.17 build system logic you too can compile while the build script is running and gate program options behind if something compiles or not.

This is not limited to Zig either, anything supported by the zig build system (i.e. C and C++) will seamlessly work.

Clone the repo, run the command and watch the magic happen:

$ zig build -Dtest=true
test_compiles_zig src/good.zig: success
test_compiles_zig src/bad.zig: failure
test_compiles_c src/good.c: success
test_compiles_c src/bad.c: failure
test_linking libcurl: success
test_linking sdl3: success
test_linking invalid: failure

the output may vary depending on available system libaries and compiler capabilities, no warranty is provided and by running the project you agree that the author cannot be held liable for any claim, damages or other liabilities.

Is this a supported use-case by upstream?

No, upstream has specifically said that this is not supported and probably will never be.

4 Likes

This is gonna come up but I don’t want to distract from the main post:


WHY

The Zig build system does not lend itself well for porting non-zig software that already made heavy use of existing build systems, such as the previously mentioned cmake, meson or autoconf, because those build systems expect a lot more system checking and integration.

For example: a project with an optional X11 implementation may check if the relevant libraries are installed and if they aren’t then it skips that implementation entirely.

With that in mind, ports of applications such as SDL simply do not work because of the mountain of different combinations in which it can be compiled and used, every port to date has enabled or hardcoded a dozen options because there is no other way.

Personally I think that to be a good C build system this functionality is needed but discussing it with upstream it was made clear to me that the Zig build system is not a C build system, this project still remains as an experiment to see if I can force the square into the round hole.

2 Likes

Love this, nice work. I actually needed something similar for a port I’m working on.

I also have a working equivalent to meson’s configure_file that I should put up on codeberg too.

2 Likes

ooo, that sounds neat.

Incase you are not aware, Zig also has a similar system in the stdlib: std.Build.addConfigHeader

Yeah, I’m using that too, but it creates a header from a set of values, rather than taking in a LazyFile and modifying found template values.

Edit: TIL addConfigHeader does in fact work in other styles too, and can take templates. Awesome.

2 Likes