How to make the Zig build system emit a c-header along with a generated library

876 Views Asked by At

Calling zig build-lib -femit-h my_lib_source.zig, a c-header file can be exported for a library written in zig.

How can the same be achieved in build.zig?

Could this be achieved with an option to b.installArtifact?

I found no documentation about this at https://ziglearn.org/chapter-3/.

2

There are 2 best solutions below

4
Der_Teufel On

Assuming you've created a lib compile step as const lib = b.addStaticLibrary(...) you can write

const install_header = b.addInstallFile(lib.getEmittedH(), "include");
b.getInstallStep().dependOn(install_header);

which should install the generated header file into a folder called include inside zig-out

1
Dave Lancea On

I looked into this a bit and I believe getEmittedH is currently broke. Maybe it works if you're also compiling an exe from a .c file (like the official documentation shows) but compiling a zig library by itself getEmittedH() puts the .h in the wrong directory (see this GitHub issue: https://github.com/ziglang/zig/issues/18497).

Adding

_ = lib.getEmittedH();

after

   b.installArtifact(lib);

does create the .h, but it's in the root of zig-cache.