https://github.com/ringtailsoftware/zig-embeddir
Example showing how to embed a directory of files in a zig executable
https://github.com/ringtailsoftware/zig-embeddir
Last synced: 10 months ago
JSON representation
Example showing how to embed a directory of files in a zig executable
- Host: GitHub
- URL: https://github.com/ringtailsoftware/zig-embeddir
- Owner: ringtailsoftware
- Created: 2023-02-13T20:06:21.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2025-01-02T00:08:51.000Z (about 1 year ago)
- Last Synced: 2025-04-10T22:40:50.399Z (10 months ago)
- Language: Zig
- Size: 380 KB
- Stars: 14
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# embeddir
An example of using the zig build system to aid in embeddeding multiple files in an executable.
Toby Jaffey, https://mastodon.me.uk/@tobyjaffey
Zig has `@embedFile` (https://ziglang.org/documentation/master/#embedFile) which embeds the contents of a file in the executable at compile time. In some situations, it's useful to embed all files from a directory without hardcoding their names into the source code.
# How does it work?
In `build.zig`, we add a custom function `addAssetsOption()`. This opens the `assets` directory, lists files and passes the list to the main program in a module called `assets` in a field called `files`.
...
options.addOption([]const []const u8, "files", files.items);
exe.step.dependOn(&options.step);
const assets = b.createModule(.{
.source_file = options.getSource(),
.dependencies = &.{},
});
exe.addModule("assets", assets);
...
In `src/main`, we build a `ComptimeStringMap` using `assets.files` as the keys and the result of `@embedFile()` on each key as the value.
At runtime, the data can then be accessed by filename using:
const data = embeddedFilesMap.get(filename).?;
The list of files can be found in `assets.files`