Search code examples
buildzig

Getting the list of all the source files in the directory passed in Zig


I am trying to write a build code in Zig and I want to loop through my project files to get the source files *.c and *.cpp. For that I have copied the following fragment of code from this website:

    pub fn addSources(directory: []const u8, b: *std.build.Builder) ArrayListAligned{
    //Searching for source files
    var sources = std.ArrayList([]const u8).init(b.allocator);

    {
        var dir = try std.fs.cwd().openDir(directory, .{ .iterate = true });

        var walker = try dir.walk(b.allocator);
        defer walker.deinit();

        const allowed_exts = [_][]const u8{ ".c", ".cpp" };

        while (try walker.next()) |entry| {
            const ext = std.fs.path.extension(entry.basename);
            const include_file = for (allowed_exts) |e| {
                if (std.mem.eql(u8, ext, e))
                    break true;
            } else false;

            if (include_file) {
                try sources.append(b.dupe(entry.path));
            }
        }
    }
    return sources.items;
}

However, I am getting the error use of undeclared identifier 'ArrayListAligned'. From what I understand I am supposed to return a slice of sources. But, I don't know Zig enough to understand what that means. Any help will be greatly appreciated.

EDIT: I am using Zig 0.9.1 for this.


Solution

  • First, the error: use of undeclared identifier 'ArrayListAligned'. This is because ArrayListAligned is not defined in the scope, you would need to use std.ArrayListAligned but this is likely not what you meant to do.

    @compileLog(@TypeOf(sources.items)) shows that it is a [][]const u8 (slice of constant slice of u8), so the return value should be [][]const u8, not ArrayListAligned

    From what I understand I am supposed to return a slice of sources

    A slice is a type in the zig language representing a many-item pointer and a length. []u8 is a slice of u8 values. Since each source is []const u8, a slice of sources would be [][]const u8 (or []const []const u8)