【问题标题】:zig creates a C library but not usable by Czig 创建了一个 C 库,但 C 不能使用
【发布时间】:2020-12-07 18:19:10
【问题描述】:

我可以让 Zig 创建一个 C 库,但是当我尝试从 C 程序中使用该库时,它无法找到包含函数的定义。

我的库定义:

const std = @import("std");

export fn removeAll(name: [*]const u8, len: u32) u32 {
    const n: []const u8 = name[0..len];
    std.fs.cwd().deleteTree(n) catch |err| {
        return 1;
    };
    return 0;
}

test "basic remove functionality" {
}

build.zig

const Builder = @import("std").build.Builder;

pub fn build(b: *Builder) void {
    const mode = b.standardReleaseOptions();
    const lib = b.addStaticLibrary("removeall", "src/main.zig");
    lib.setBuildMode(mode);
    switch (mode) {
        .Debug, .ReleaseSafe => lib.bundle_compiler_rt = true,
        .ReleaseFast, .ReleaseSmall => lib.disable_stack_probing = true,
    }
    lib.force_pic = true;
    lib.setOutputDir("build");
    lib.install();

    var main_tests = b.addTest("src/main.zig");
    main_tests.setBuildMode(mode);

    const test_step = b.step("test", "Run library tests");
    test_step.dependOn(&main_tests.step);
}

zig build 使用libremoveall.a 静态库创建构建目录。

我的 C 程序:

#include <stdio.h>

int removeAll(char *, int);

int main(int argc, char **argv)
{
    removeAll("/tmp/mytest/abc", 15);
    return 0;
}

当我尝试将它包含在我的 C 程序中时,它得到以下错误:

gcc -o main build/libremoveall.a main.c
/usr/bin/ld: /tmp/cckS27fw.o: in function 'main':
main.c:(.text+0x20): undefined reference to 'removeAll'

关于我做错了什么有什么想法吗? 谢谢

编辑

感谢 Paul R 和 stark,翻转订单成功了。你能帮我理解为什么顺序很重要吗?

【问题讨论】:

  • 尝试在命令行切换 main.c 和 lib 的顺序。
  • 把库放在main.c之后
  • 我还建议对 .a 文件进行 objdump -ing 以确保该函数实际上也存在。

标签: c zig


【解决方案1】:

链接器在库中搜索到目前为止在该过程中遇到的未解析引用。

如果您将程序放在库之后,则链接器读取库时没有未解析的引用。然后当它读取你的程序时,没有库可以解析引用。

交换您的程序和库,一切就绪。

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多