zig creates a C library but not usable by C

跟風遠走 提交于 2021-01-02 16:17:04

问题


I'm able to get Zig to create a C library but when I attempt to use said library from a C program, it fails to find the definition of the included function.

My library definition:

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 creates the build directory with the libremoveall.a static library.

My C program:

#include <stdio.h>

int removeAll(char *, int);

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

When I attempt to include it in my C program, it get the following error:

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'

Any ideas on what I'm doing wrong? Thanks

EDIT

Thanks Paul R and stark, flipping the order worked. Can you help me understand why the order matter?


回答1:


The linker searches a library for unresolved references encountered so far in the process.

If you put your program after the library, there are no unresolved references when the linker reads the library. And then when it reads your program, there is no library to resolve the reference.

Swap your program and the library, and you are all set.



来源:https://stackoverflow.com/questions/65187214/zig-creates-a-c-library-but-not-usable-by-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!