Zig开发C可调用库时构建缺失导出头文件的问题排查与解决
Zig开发C可调用库时自动生成头文件缺失问题解决
问题背景
基于Zig 0.6版本官方文档「导出C语言库」「混合目标文件」两个示例开展实践,从文档中拷贝了三类关联文件:
- 作为调用方的C语言文件test.c
- 两个示例对应的Zig源文件(导出C库示例使用mathtest.zig,混合目标文件示例使用base64.zig)
- 对应项目的构建脚本build.zig
但两个示例均构建失败:编译C调用文件时提示找不到Zig本该自动生成的对应头文件(mathtest.h/base64.h)。
以下为导出C库示例的原始项目文件:
mathtest.zig
export fn add(a: i32, b: i32) i32 { return a + b; }
test.c
// This header is generated by zig from mathtest.zig #include "mathtest.h" #include <stdio.h> int main(int argc, char **argv) { int32_t result = add(42, 1337); printf("%d\n", result); return 0; }
原始build.zig
const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0)); const exe = b.addExecutable("test", null); exe.addCSourceFile("test.c", &[_][]const u8{"-std=c99"}); exe.linkLibrary(lib); exe.linkSystemLibrary("c"); b.default_step.dependOn(&exe.step); const run_cmd = exe.run(); const test_step = b.step("test", "Test the program"); test_step.dependOn(&run_cmd.step); }
报错信息
执行zig build test命令时输出如下错误:
~/Projects/zig/z-c-lib $ zig build test /home/robert/Projects/zig/z-c-lib/test.c:2:10: fatal error: 'mathtest.h' file not found #include "mathtest.h" ^~~~~~~~~~~~ 1 error generated. The following command failed: /home/robert/zig/zig clang -c -nostdinc -fno-spell-checking -target x86_64-unknown-linux-gnu -isystem /home/robert/zig/lib/zig/include -isystem /home/robert/zig/lib/zig/libc/include/x86_64-linux-gnu -isystem /home/robert/zig/lib/zig/libc/include/generic-glibc -isystem /home/robert/zig/lib/zig/libc/include/x86_64-linux-any -isystem /home/robert/zig/lib/zig/libc/include/any-linux-any -Xclang -target-cpu -Xclang znver2 -Xclang -target-feature -Xclang -3dnow -Xclang -target-feature -Xclang -3dnowa -Xclang -target-feature -Xclang +64bit -Xclang -target-feature -Xclang +adx -Xclang -target-feature -Xclang +aes -Xclang -target-feature -Xclang +avx -Xclang -target-feature -Xclang +avx2 -Xclang -target-feature -Xclang -avx512bf16 -Xclang -target-feature -Xclang -avx512b
系统中完全检索不到文档提及的、本该由Zig自动从Zig源文件生成的mathtest.h文件。
问题排查过程
- 手动执行
zig build-lib mathtest.zig -femit-h命令可直接生成mathtest.h头文件,生成后再执行常规构建流程即可成功编译运行。 - 在build.zig的共享库配置项中添加以下配置:
即可让const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0)); lib.femit_h = true;zig build test流程正常运行,输出预期计算结果1379;但此配置下构建完成后,生成的头文件不会留存到项目当前目录,无法直接提供给C侧使用。
最终解决方案
在build.zig的共享库配置中追加lib.setOutputDir("build")设置,即可让生成的mathtest.h头文件与编译产出的libmathtest.a/libmathtest.so库文件统一保存到build目录下,完成Zig开发C可调用库的全流程搭建。
内容的提问来源于stack exchange,提问作者roblackwell
相关产品推荐
相关产品推荐

