已关闭 - 请参阅条目末尾
我想使用zig语言制作一个C可调用库。 我决定从 Zig 文档中的两个示例开始。 “导出 C 库”和“混合目标文件”。 在每种情况下,我都复制了三个相关文件(来自 0.6.0 文档)。
两个示例均无法构建。
导出 C 库示例无法编译 test.c,并显示消息无法找到 mathtest.h
混合对象文件示例无法编译 test.c,并且找不到 base64.h
以下是导出 C 库示例的三个文件:
数学测试.zig
export fn add(a: i32, b: i32) i32 {
return a + b;
}
测试.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);
}
部分错误信息
~/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
我在我的系统上找不到名为
mathtest.h
的文件,因此我认为它没有生成,这与 test.c 文件中的声明相反。
我错过了什么?帮助感激不尽。
答案和更多问题
我发现了
-femit-h
选项:
zig build-lib mathtest.zig -femit-h
将创建一个
mathtest.h
文件,然后
zig build
一定会成功。
我进一步发现
build.zig
文件中的这些行
const lib = b.addSharedLibrary('mathtest', 'mathtest.zig', b.version(1, 0, 0));
lib.femit_h = true;
将确保
zig build test
将会成功并生成答案 1379,如文档中所示。
但是 - build.zig 文件的此 mod 在运行后不会留下
mathtest.h
文件。
这似乎是从 Zig 代码生成可用的 C 库的最后障碍。
拼图中的最后一块
如果我添加
lib.setOutputDir("build");
到
build.zig
文件。 mathtest.h
和 libmathtest.a
(或 .so)文件将保存到 build
目录中。
就这样结束吧
好吧,部分答案很简单,但可能比较晦涩,就是 -femit-h 选项。 命令
zig build-lib mathtest.zig -femit-h
将生成一个
mathtest.h
文件。
但是我如何将该选项添加到
const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));
build.zig 文件中的行。