A simple to use C++ build system wihout the headaches of cmake.
  • C++ 95.6%
  • JavaScript 3.5%
  • Shell 0.4%
  • C 0.3%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Jorijn van der Graaf 9df82bc272
docs: where a source's object goes, and what a link reads
The README's "Writing a project.cpp" says that a .cpp, .c or .cu of a
configuration is compiled into an object named from its path, under
objects/ in the build directory at the source's path from cfg.path, or
under objects-outside/ at its whole path for a source outside
cfg.path; that two sources may therefore have the same file name in
different directories, and a .c lie beside a .cpp or a .cu of its
name; that the progress line of such a source's compile names it by
that path; and that the link and a static library's archive step read
their objects from <outputName>.objects in the build directory.

The contributor guide gains two rules beside the one on output paths.
ObjectPath() names an object, which is not to be named from its
source's file name, and a step that takes every object of a
configuration reads them from a response file. And a static library's
archive and the list of a step's objects are written under another
name beside them and renamed into place, as anything else that a link
or archive step of another crafter-build may be reading is to be: two
crafter-builds can build a project loaded with GitProject at once, in
the clone the cache keeps for its source.
2026-11-19 11:02:39 +01:00
.forgejo/workflows feat(ci): drop beta and latest, release signed tags on master 2026-11-02 17:17:02 +01:00
.review-gates feat: let a project file return several configurations 2026-11-15 02:16:06 +01:00
examples docs: wasm exceptions as the review left them 2026-10-31 06:10:41 +01:00
implementations fix(build): name a source's object from its path 2026-11-19 11:02:39 +01:00
interfaces fix(build): name a source's object from its path 2026-11-19 11:02:39 +01:00
lib removed json.hpp 2026-10-06 17:05:42 +02:00
packaging/flatpak docs(packaging): add the 6.4.0 release entry 2026-11-15 02:16:07 +01:00
tests test(build): sources of one file name, and where their objects go 2026-11-19 11:02:39 +01:00
wasi-runtime fix(wasm): what the review found 2026-10-31 06:10:41 +01:00
.gitignore feat(review): set up Crafter.Review's pre-push review 2026-11-01 17:33:27 +01:00
AGENTS.template.md docs: where a source's object goes, and what a link reads 2026-11-19 11:02:39 +01:00
build.sh feat(build): run a build's steps on one worker per hardware thread 2026-11-13 17:59:55 +01:00
LICENSE SPDX license update 2026-07-22 18:19:17 +02:00
LICENSE.GPL SPDX license update 2026-07-22 18:19:17 +02:00
project.cpp test(build): sources of one file name, and where their objects go 2026-11-19 11:02:39 +01:00
README.md docs: where a source's object goes, and what a link reads 2026-11-19 11:02:39 +01:00

Crafter Build

A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a project.cpp that constructs a Configuration, or several, and returns them. Crafter Build compiles, loads, and executes it.

Install

crafter-build ships as a Flatpak that carries its own clang, lld, libc++ and WASI sysroot, so every machine builds with the same compiler, and lldb and the Vulkan validation layers to debug the result (see Debugging):

flatpak remote-add --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo
flatpak install catcrafts net.catcrafts.CrafterBuild
alias crafter-build='flatpak run --die-with-parent net.catcrafts.CrafterBuild'

--die-with-parent ends the sandbox with the flatpak run that started it. Without the flag, killing only the flatpak run process leaves the sandbox running: a build carries on writing into bin/ and build/, and a program started with -r keeps running. With it, bubblewrap kills everything in the sandbox with SIGKILL when the flatpak run process dies or when that process's parent does. For crafter-build … or crafter-build … & typed at a bash or zsh prompt, that parent is the shell, so the sandbox ends with the shell, even after a disown. Ctrl-C reaches the program either way.

Releases are published to the stable branch that the commands above install, and every release also attaches a single-file bundle on the Forgejo releases page (flatpak install --user crafter-build-<version>.flatpak). The sandbox sees the host's own files where it shares them, the home, /mnt, /opt, /srv and /run/media among them, so a project can live there; it has its own /tmp, /var, /usr, /etc and /app. Binaries built for the host link the bundled libc++.so.1 through an rpath into the Flatpak: they run inside it (-r, the test runner), and are not meant to be copied out onto the host. To run a program outside crafter-build's sandbox, package it as a Flatpak of its own (Flatpak output).

Writing a project.cpp

Crafter Build loads a project.cpp from the current directory. The file exports one function: CrafterBuildProject, which returns a populated Configuration, or CrafterBuildConfigurations for several:

import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;

extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
    Configuration cfg;
    cfg.path = "./";
    cfg.name = "myapp";
    cfg.outputName = "myapp";
    cfg.type = ConfigurationType::Executable;

    std::array<fs::path, 1> ifaces = { "interfaces/Hello" };
    std::array<fs::path, 2> impls  = { "implementations/Hello", "implementations/main" };
    cfg.GetInterfacesAndImplementations(ifaces, impls);

    return cfg;
}

Run crafter-build in that directory, outputs land at bin/myapp-<target>-<march>-<mtune>-<hash>/myapp and intermediates at build/myapp-<target>-<march>-<mtune>-<hash>/. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. crafter-build clean removes the ones left behind. Add -r to run the produced executable straight after a successful build, in its own directory, where its shaders, cfg.files and assets are; a wasm32 one runs under wasmtime, or wasmer where there is no wasmtime, with no directory given to it, and one built for the browser (EnableWasiBrowserRuntime) is served over HTTP from that directory instead.

A .cpp, .c or .cu of a configuration is compiled into an object named from its path: a/Thing.cpp into objects/a/Thing_impl.o in that build/ directory, at the source's path from cfg.path, and a source outside cfg.path into objects-outside/ there, at its whole path. Two sources may therefore have the same file name in different directories, and a .c may lie beside a .cpp or a .cu of its name. The progress line of such a source's compile names it by the same path, Compiling a/Thing.cpp. The link, and the archive step of a static library, read their objects from a file in that directory, <outputName>.objects, so the command is no longer for many sources than for one.

crafter-build orders a configuration's units by the import lines of its sources: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused before anything of it is built, with an error that names the units in the order they wait. The imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under #if 0 counts too, and such text can make a round in a project the compiler accepts.

A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An ExternalDependency's CMake build is not among them and is given that many jobs of its own, and the tests crafter-build test runs are counted by --jobs=. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts.

Several configurations

A project that builds more than one thing, such as a library and the tool that comes with it or the programs of one repository, returns all of them from CrafterBuildConfigurations instead. They need not have anything to do with each other, and crafter-build builds every one of them:

extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view> args) {
    static std::deque<Configuration> owned;

    Configuration& lib = owned.emplace_back();
    lib.path = "./";
    lib.name = "mylib";
    lib.outputName = "mylib";
    lib.type = ConfigurationType::LibraryStatic;
    std::array<fs::path, 1> libIfaces = { "interfaces/MyLib" };
    std::array<fs::path, 1> libImpls  = { "implementations/MyLib" };
    lib.GetInterfacesAndImplementations(libIfaces, libImpls);

    Configuration& tool = owned.emplace_back();
    tool.path = "./";
    tool.name = "mytool";
    tool.outputName = "mytool";
    tool.type = ConfigurationType::Executable;
    tool.dependencies = { &lib };
    std::array<fs::path, 0> toolIfaces = {};
    std::array<fs::path, 1> toolImpls  = { "implementations/main" };
    tool.GetInterfacesAndImplementations(toolIfaces, toolImpls);

    return { &lib, &tool };
}

A project file has one of the two functions, never both. CrafterBuildConfigurations gets the same args as CrafterBuildProject, and ProjectArgs() and IsTopLevelProject() answer the same inside it. It returns pointers, so the configurations have to stay where they are for as long as crafter-build runs. A std::deque that the file only adds to keeps them there, with a new set for every call; a std::vector would move them when it grows, and a single static Configuration would be filled in again by every load of the file. A pointer that GitProject or LocalProject returned can be in the list as well, which is how one file builds a set of sibling projects.

With several configurations:

  • A build builds all of them in one pass, so what two of them depend on is built once. One that fails does not stop the others, and the build then fails with the errors of the ones that failed.
  • test runs the tests of every one the file made itself, in one run. By default a test is built from tests/<Name>/ into build/<Name>-<variant>/ and bin/<Name>-<variant>/, whichever configuration declares it, so a test belongs to one of them: where two each declare a test that would be built into the same directories, both tests fail without being built and name the two configurations. Give each test a name of its own.
  • run offers the scripts of every one the file made itself: a script gets the configuration it is declared on as ctx.project, and a name two of them declare is an error.
  • lint and format take the rules and the sources of every one that lies in the project's directory, and a rule two of them register under one name runs once.
  • -r runs the executable when exactly one of them is one, and install and bundle export the one that is packaged as a Flatpak. With more than one to choose from they stop and name them, as install and bundle do when none is packaged: -r once everything is built, install and bundle before anything is.
  • A configuration of another project, which the file got from GitProject or LocalProject and returns, is built with the rest and counts for -r, install and bundle. Its tests and its scripts stay that project's.
  • Two that would be built into the same directory, as two with the same path and name and no other difference are, are refused by a build, test, -r, install and bundle, before anything is built. Give each a name of its own. A build, -r, install and bundle refuse two more sets before they build anything: configurations that are each built on something of another's directory, so that none could be built first, and one that is built on something of its own directory when another is built on that directory as well.
  • cfg.dependencyNotes is read on every one the file made itself (see Dependency notes for agents).

Flatpak output

A program crafter-build's Flatpak links for Linux without a sysroot takes the libc++, libc++abi and libunwind of its LLVM and the glibc of its runtime, so outside the Flatpak it starts only on a host that has those libraries and a glibc with every symbol version they and the program reference, 2.38 or newer for the bundled libc++. A build lays the program out as a Flatpak of its own when it is packaged:

cfg.packaging = Packaging::Flatpak;   // or, for one build: --packaging=flatpak, where project.cpp calls ApplyStandardArgs

Its bin directory then holds files/, what becomes /app inside the app's sandbox:

bin/myapp-<variant>/
└── files/
    ├── bin/      myapp and the files it reads beside it: shaders, cfg.files, assets
    ├── lib/      libc++, libc++abi, libunwind, and the shared libraries it links from its dependencies and from crafter-build's /app/lib
    └── share/    the desktop entry, metainfo and icons under the app-id, and cfg.flatpak.share

-r runs files/bin/myapp from that directory, inside crafter-build's sandbox, against the libraries in files/lib, the ones the app carries. To install the app for yourself, or to hand it to someone else:

crafter-build install     # build it and install it for this user: `flatpak run local.crafterbuild.myapp`
crafter-build bundle      # build it into bin/myapp-<variant>.flatpak, for `flatpak install --user <file>`

Both make the app first. Without modules, crafter-build makes build/flatpak-apps/<app-id>/build-dir of files/, as hard links to the build's own where they can be made and copies where they cannot, and a metadata naming the app, its runtime and the Sdk, and the host's flatpak build-finish finishes it by flatpak's own rules: it adds the command and the sandbox's permissions to the metadata and writes export/, what the host sees of the app, such as its desktop entry and icons. With modules, flatpak-builder does all of it.

install puts the app into a repo of the project's, in build/flatpak-apps/<app-id>/, and installs it from a user remote named crafter-build-<app-id>, updating what an earlier install left; it prints how to remove both, which matters before crafter-build clean deletes the repo. Installs of one app-id from two checkouts take turns on that remote, by a lock in ~/.cache/crafter.build/flatpak-remotes/ that every crafter-build installing for the user takes, the Flatpak's too. bundle writes a single file that flatpak install --user installs, naming Flathub's repository in it for the runtime. install takes the runtime from an installation that has it, the system's or the user's, or from a remote of the user's installation; where none does, flatpak stops with requires the runtime ... which was not found, and flatpak install flathub org.freedesktop.Platform//26.08, or the Sdk for an app that runs on it, puts it in place. An app with modules needs org.freedesktop.Sdk//26.08 whatever it runs on, since flatpak-builder makes it with that: flatpak install flathub org.freedesktop.Sdk//26.08. Both run the host's flatpak, and with modules its flatpak-builder, which crafter-build's Flatpak reaches through the Flatpak session helper (the org.freedesktop.Flatpak permission) and uses for nothing else. The permission belongs to the whole sandbox, so a project.cpp, its scripts, the builds of its dependencies and the programs -r and test start can reach the host through it too; through the sandbox's --filesystem=host they could already write files the host runs, such as ~/.bashrc. The host sees the project at the path crafter-build does where the sandbox shares the host's directories, as it does the home, /mnt, /opt, /srv and /run/media, and not in the sandbox's own /tmp, /var, /usr, /etc and /app. Before building, install and bundle ask the host whether it sees the project's bin/ and build/ where crafter-build does, following their links as the host does: they start its flatpak in a directory made in each for the question and removed again, and refuse the project where it cannot start there. To try the app on the host without installing it, run flatpak build --runtime --readonly build/flatpak-apps/<app-id>/build-dir myapp there after an install or bundle: it runs on the app's runtime, with the filesystems and the environment its metadata grants.

Installed, the program starts in the directory it is started from, when its permissions let it see that directory, and in $HOME otherwise. A program that reads its own files therefore finds them next to its executable (/proc/self/exe) rather than in the working directory, which is only its own under -r.

What the app is installed as is cfg.flatpak; a hello world sets none of it:

cfg.flatpak.appId = "net.example.MyGame";              // default: local.crafterbuild.<outputName>
cfg.flatpak.runtime = FlatpakRuntime::Sdk;             // default Platform; the Sdk has git, gcc and the like
cfg.flatpak.permissions = { "--socket=pulseaudio" };   // finish-args, spelled as in a Flatpak manifest
cfg.flatpak.desktopFile = "packaging/MyGame.desktop";  // installed as <appId>.desktop; its Icon= is the app-id
cfg.flatpak.metainfo = "packaging/MyGame.metainfo.xml";
cfg.flatpak.icons = { "packaging/icon.svg" };          // an .svg is scalable, a square .png goes under its size
cfg.flatpak.share = {                                  // under /app/share, not beside the program like cfg.files
    { "data", "mygame/data" },                         // a directory: every regular file in it, at its path inside it
    { "LICENSE", "licenses/net.example.MyGame/LICENSE" },
};
cfg.flatpak.modules = { "packaging/flatpak/node.yaml" }; // flatpak-builder modules for more in /app
  • Permissions are the sandbox's: sockets, devices, shares, filesystems, bus names, environment. A library declares what every program built on it needs in its own cfg.flatpak.permissions, and those reach the program before the program's own, which can take one back (--nosocket=x11). install and bundle print the resulting list, with where each came from, and hand it to flatpak build-finish, which refuses a misspelled argument, and a share, socket, device or feature flatpak does not have, naming the ones it has. The build itself does not read them, so changing one builds nothing.
  • The runtime is always at the branch crafter-build runs on (26.08 today), since the program links that runtime's glibc. The Platform is enough to run a program; the Sdk is for one that runs tools such as git at run time.
  • Share entries are files of the project the program reads from /app/share instead of from beside itself: data it finds at <its directory>/../share/<name>, licences. files/share is the build's own, so they are kept there as long as they are listed and removed once they are not, and anything else put there is removed too. -r runs the program from files/bin, so the same ../share lookup finds them. Any file can be one, a second desktop entry or an add-on's metainfo among them: what flatpak exports of an app's share/, it exports of them too, by its own rules, such as an icon, D-Bus service, MIME package, search provider or KRunner plugin named after the app-id. flatpak build-export refuses an exported icon that is not a square image and a D-Bus service that is not a key file, and warns of the app's own desktop entry where desktop-file-validate rejects it; a second desktop entry, a MIME package or metainfo it exports as it is. A directory entry places every regular file in it, and every link to one, at its path inside it; anything else in it is left out: empty directories, links to directories, dangling links, FIFOs and sockets. Two files for one path in share/, a field's own file among them, or a file where another entry needs a directory, fail the build. The app's desktop entry, applications/<app-id>.desktop, is held to desktopFile's checks whichever placed it. A directory that holds what the build writes fails too, since it would be copied into itself, growing each time the app is built or exported: files/, and the app's directory in build/flatpak-apps/, where install and bundle put another copy of files/ and the exported app, the project's own directory holding both, as written and where links lead, so also where bin/ is a link elsewhere. So does one that lies in them, which is the build's own output.
  • Modules are for what the app needs in /app besides the program: a runtime it starts, a tool it runs, data built from source. They are flatpak-builder module files in Flatpak's own format, which crafter-build names and never reads. With any, install and bundle have the host's flatpak-builder (or the org.flatpak.Builder app) make the app with org.freedesktop.Sdk//26.08, which the host then needs as well as the runtime, from a manifest in build/flatpak-apps/<app-id>/ that lists them and copies the built program in last, so it is not compiled again; flatpak-builder's defaults then also strip it and split its debug info into a .Debug extension. Translations under share/locale stay in the app rather than going into a .Locale extension, which a bundle would leave out. -r runs the program without them.
  • What cannot be a Flatpak fails the build saying why: Windows and wasm targets, which keep their .exe and .wasm; a build against a sysroot, which links that sysroot's libraries and not the runtime's, or one for musl, a C library no runtime has; an architecture other than the runtime's; a build against CRAFTER_BUILD_LIBCXX_DIR, since a Flatpak carries the toolchain's own libc++, built against the runtime's glibc; and a build by a native crafter-build, whose programs link the host's glibc, unless CRAFTER_BUILD_FLATPAK_INFO, which the tests set, names a runtime. A dependency's executables stay as linked even when --packaging=flatpak reaches their project, since their consumers run them by path, and tests are never packaged. A dependency that sets cfg.packaging in its own project.cpp is packaged, and the files its cfg.flatpak names are found in its own directory, as its cfg.files are.
  • For other machines, build with --march=x86-64-v3 rather than the default native, which can crash with SIGILL on an older CPU. Pass it on the command line or in CRAFTER_BUILD_MARCH: either reaches every configuration of the program that ApplyStandardArgs is called on, a sibling's whose project.cpp calls it included, while CMake externals are compiled without -march, and a #pragma crafter dependency, tooling built for project.so alone, with -march=native. A program with CUDA sources also needs a --cuda-arch= other than native, such as all-major (see CUDA), and bundle warns of a bundle built for either native.

Without packaging (Packaging::None, and for now Default), a program is the executable as linked: it runs inside crafter-build's sandbox (-r, test, run scripts), and on a host only where the host has what it links.

Dependencies

Three kinds, all fetched/built incrementally:

Cross-project Crafter sub-projects — point cfg.dependencies at another Configuration*. Cross-project module imports (import OtherProject;) are tracked per-import: only the modules that actually import a changed dep rebuild. A dependency's headers reach the C++ and C compiles of the projects built on it by themselves: its directory and every directory named include in its tree are on their include path, except those under a directory named bin or build, where builds leave their output. A header kept under one of those needs an -I of its own in the cfg.compileFlags of the projects that include it. A cfg.cuda source gets neither.

External git+cmake deps — for things like glslang. Declare in cfg.externalDependencies:

ExternalDependency& glslang = cfg.externalDependencies.emplace_back();
glslang.name = "glslang";
glslang.source.url = "https://github.com/KhronosGroup/glslang.git";
glslang.source.branch = "main";
glslang.builder = ExternalBuilder::CMake;
glslang.options = { "-DENABLE_OPT=OFF" };
glslang.includeDirs = { "" };
glslang.libs = { "SPIRV", "glslang", "OSDependent" };

Clones live at ~/.cache/crafter.build/external/<name>-<hash>/, keyed by (url, branch, commit, options, target) so different projects sharing the same dep with the same spec reuse the clone and cmake build, while projects with diverging specs each get their own cache entry. Without a commit, the clone is git pulled once per build: every configuration of the build that declares the dependency, such as each test of a project whose tests copy its externalDependencies, shares that one fetch and cmake build. The clone is resilient to partial-clone recovery and CMake reconfigure is triggered automatically on options changes. Submodules are checked out at the revisions the fetched commit records, after every clone, switch, checkout and pull, so a pinned commit builds against its own submodules and not the default branch's.

Header-only git deps — same as cmake deps but builder = ExternalBuilder::None. Just clones and propagates -I flags.

Sibling crafter-build projects — GitProject / LocalProject load another project's project.cpp in-process and return a Configuration* for cfg.dependencies:

Configuration* math = GitProject({
    .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.Math.git" },  // .branch or .commit to pin
});
Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project.cpp" });
cfg.dependencies = { math };

The sibling's entry point gets the args this project.cpp was loaded with (ProjectArgs()), so --target=, --march=, --debug and the project's own flags reach every sibling down the chain. That is all of them: cfg.projectArgs holds only what ApplyStandardArgs did not interpret, and passing it on would drop the target and the build type. Set .args to send something else: {} for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths. Releases up to 2.2.0 forward nothing when .args is left out.

The default is read when the spec is made, so make it inside the entry point, CrafterBuildProject or CrafterBuildConfigurations, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing.

Clones share the external cache and identical specs share one Configuration. An unpinned source is git pulled on every invocation, set .commit for reproducible, offline-after-first-fetch builds.

A sibling whose project file returns several configurations gives its first one, or the one .configuration names by its name:

Configuration* packer = LocalProject({ .projectFile = "../tools/project.cpp", .configuration = "packer" });

Only the configuration a consumer names is built for it, with what that one depends on, and specs that differ only in .configuration share one load of the sibling. A name the sibling does not have is an error that lists the ones it has, and a name two of its configurations share is an error too. A library that comes to return a second configuration puts it after the first, so that a consumer that names none keeps getting the one it had. Its consumers then need a crafter-build that has CrafterBuildConfigurations: an older one loads only a CrafterBuildProject.

A project loaded this way runs its entry point as a dependency, and IsTopLevelProject() is false while it does (true in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's project.cpp from inside crafter-build and recurse.

Dependencies of project.cpp itself

project.cpp can import modules from another crafter-build project. The file has to compile before it can say anything, so the dependency is a directive next to the import it enables:

import std;
import Crafter.Build;
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git"
import Crafter.LintRules;
#pragma crafter dependency "<source>" [branch "<name>" | commit "<sha>"] [project "<file>"]

Such a dependency is built for the host, whatever the project targets, and its project.cpp gets none of the project's args. Of a project that returns several configurations, the dependency is the first.

Dependency notes for agents

An agent working on a project reads its AGENTS.md, which says nothing about the libraries the project builds against unless someone copied that in by hand. A library ships it instead: an AGENTS.consumer.md beside its project.cpp, written for whoever uses the library rather than whoever works on it.

A consumer that wants its dependencies' notes writes its own instructions in an AGENTS.template.md beside its project.cpp, and commits that instead of an AGENTS.md. crafter-build, crafter-build test, crafter-build install and crafter-build bundle then write AGENTS.md from the template with the notes added, so AGENTS.md is build output and stays out of version control: a dependency that changes its notes changes nothing a diff shows. A project with a committed AGENTS.md moves over from the directory of its project.cpp:

git mv AGENTS.md AGENTS.template.md
echo /AGENTS.md >> .gitignore

What a build then writes:

<!-- Written by crafter-build from AGENTS.template.md, and rewritten on every build. Edit that file, not this one. -->
# The template's text

...

<!-- crafter-build: dependency notes begin -->
<!-- Written by crafter-build from the AGENTS.consumer.md each dependency ships, and rewritten on every build. Edit those files, not this section; cfg.dependencyNotes in project.cpp picks which dependencies are included. -->

<!-- from Crafter.Math -->
## Crafter.Math

...

<!-- crafter-build: dependency notes end -->
  • Each file goes in as written, under a line naming the dependency: its repository's name, or a LocalProject's directory name. That reads the same on every machine, and for a --local checkout and its git clone alike. The file lands among the consumer's own headings, so start it with a ## heading that names the library.
  • The section goes after the template's text and a blank line. To have it elsewhere, put the begin and end marker lines in the template where it should go: whatever they enclose is replaced. A template moved over from a committed AGENTS.md has them where its section was, around notes that can be deleted.
  • AGENTS.md is written only when its text changes, in place, so a CLAUDE.md linked to it, its ownership and a read-only AGENTS.md are respected. An edit made in it is gone after the next build, and a fresh clone has none until its first build. The template is never written.
  • An AGENTS.md that no build wrote, such as a committed one still next to a new template, is never replaced: each build warns instead, until it is deleted. Without a template, AGENTS.md is never touched. One that still holds a section from crafter-build 3.0.0, which kept the notes in a committed AGENTS.md, gets a warning: move it over as above, or delete the section.
  • In a build or a test run that is not refused before it starts, the update runs once project.cpp has loaded and before the project compiles, so a build that fails while it compiles still has the notes. It does not run for a project.cpp that fails to load, for test --list, lint, format, run and clean, or for a verb that is refused before it starts a build: an install or bundle of a project that is not packaged as a Flatpak, or for which crafter-build cannot run the host's flatpak, and a build, test, install or bundle of several configurations that are refused as a set.
  • The section follows what the build loaded: a dependency that only some flags pull in (a --target=, a flag of the project's own) comes and goes with them. An unpinned dependency's notes follow its default branch, as its code does, so the section can change on any build. Pin a commit to decide when.
  • A library reached through two specs, pinned at one revision here and another further down, is described once, as the nearer one has it.
  • When there are notes to write, unbalanced markers in the template leave AGENTS.md as it is, with a warning. A notes file that would break the section (a code block it never closes, a marker line of its own) is left out, also with a warning. Markers quoted inside a fenced code block don't count.

cfg.dependencyNotes picks the dependencies:

Value Notes from
DependencyNotes::Transitive (default) everything the project builds against, all the way down: its dependencies and its own #pragma crafter dependency tooling
DependencyNotes::Direct only the projects the project's own configurations and #pragma crafter dependency lines name
DependencyNotes::None none: AGENTS.md holds the template's text alone

Three things never count: the project's own AGENTS.consumer.md; its tests' dependencies, since a plain build never looks at the tests; and a dependency's #pragma crafter dependency tooling, which is about how the dependency is built, not how it is used.

In a project of several configurations, the dependencyNotes of each one the file made itself selects among what that one is built against, and a dependency's notes are in when a configuration that asks for them leads to it: what a Direct configuration names is followed further when a Transitive one reaches it too. The project's own #pragma crafter dependency tooling, and a configuration of another project that the file returns, which counts as a dependency here, go by the widest setting among the configurations the file made itself.

CUDA

cfg.cuda lists CUDA sources, named without .cu. A relative name is read from the directory crafter-build runs in, except in a project loaded through GitProject or LocalProject, whose relative names crafter-build rebases onto that project's directory:

cfg.cuda = { fs::absolute("kernels/blur") };    // kernels/blur.cu

nvcc compiles each into an object that joins the configuration's other objects, and the configuration links the CUDA runtime of nvcc's toolkit, as does whatever is built on it: libcudart_static.a from the toolkit's lib64, with the -lrt -lpthread -ldl nvcc's own link puts after it. Being static, it takes no run path into the toolkit. It comes after cfg.linkFlags and the libraries of what the configuration is built on, so a -lcudart named there is the one the linker takes. A toolkit whose lib64 holds no libcudart_static.a, as where a distribution keeps the toolkit's libraries in its own directories, gets no runtime linked: cfg.linkFlags names it, as before.

  • The toolkit is the one CUDA_PATH names, else the first of /opt/cuda, where Arch's package installs it, and /usr/local/cuda, the link NVIDIA's installer and packages make to theirs, that has a bin/nvcc, else the first nvcc in an absolute entry of PATH. A CUDA_PATH without a bin/nvcc is an error, not a reason to look elsewhere. crafter-build --version prints the nvcc it found and, where there is one, the static runtime beside it; a build with a .cu to compile and no nvcc says where it looked.
  • In the Flatpak, /opt and your home are where the host has them, the host's /usr/local/cuda is found under /run/host, as is the toolkit it is a link to, and PATH is the sandbox's own /app/bin:/usr/bin, so for a toolkit anywhere else, set CUDA_PATH. nvcc compiles the host code with the Sdk's g++ (GCC 16.2), not the host's: NVCC_CCBIN still applies, and names a path inside the sandbox. The programs -r and test start find the driver's libcuda.so.1 in the runtime's NVIDIA GL extension for the host's driver.
  • The GPU architecture is cfg.cudaArch, nvcc's -arch. It defaults to native, the GPUs of the machine that builds, as march defaults to its CPU; where there is none, nvcc warns and uses its own default (sm_75 in CUDA 13.4). Like -march=native, it is for a program that runs where it is built: it carries no PTX, which a GPU of a newer architecture compiles when it loads the program. For other machines, build with --cuda-arch=all-major, nvcc's major architectures (sm_*0) and its earliest, with the PTX of the newest major, or name one, such as sm_89, which comes with its own PTX. --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH set it where project.cpp calls ApplyStandardArgs, as --march= and CRAFTER_BUILD_MARCH set march, and a test inherits it. Another architecture builds in a directory of its own, and so does native when the GPUs change: the NVIDIA GPUs on the machine's PCI bus (its display devices, PCI class 0x03), the slots they are in, CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER key it. That is crafter-build's reading of the machine, not nvcc's own: after a change it cannot see, such as a GPU bound to another driver, run crafter-build clean, or build with a named architecture, which depends on nothing on the machine.
  • nvcc gets -O3 and -arch, beside -c, the .cu and its outputs (-o, and -MD -MF for the depfile): none of the include paths, defines and cfg.compileFlags the C and C++ compiles get, and no -g for cfg.debug. A .cu compiles again when it, or a header it includes, is newer than its object, as a C or C++ source does.

Tests

Tests live under tests/<Name>/. The simplest case is a single C++ file:

tests/Smoke/main.cpp        # int main() — exit 0 = pass, nonzero = fail, 77 = skipped

Run them all:

crafter-build test

Test conventions:

  • Exit codes: 0 = ✅ pass, nonzero = ❌ fail, 77 = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH").
  • Each test runs in its own subprocess — a segfault doesn't take the runner down.
  • Default timeout is 60 s per test, runs in parallel up to hardware_concurrency() tests (--jobs=). The steps of their builds share one limit, a build's: as many at once as there are hardware threads.
  • Stdout+stderr is captured and printed atomically on completion. Failed/crashed/timed-out tests also write to build/test-logs/<name>.log.
  • A broken fixture project.cpp is reported as a single failed test, not a fatal error — other tests still run.

CLI:

crafter-build test                                              # run all
crafter-build test 'Unit*'                                      # glob-filter test names
crafter-build test --list                                       # enumerate without running
crafter-build test --target=x86_64-w64-mingw32                  # only tests for this target
crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine
crafter-build test --jobs=1                                     # one test at a time
crafter-build test --timeout=5                                  # override per-test timeout

Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed.

--target= filters the run to tests whose cfg.target matches, default is the host triple. Per-target tests parse --target=... from their own args span and build for it, tests with hardcoded targets (e.g. host-only meta-tests) are filtered out under non-matching --target=.

Cross-target test runners

Test::runner runs the test binary somewhere other than this machine. Four factories:

TestRunner::Local()                                  // run on this machine (default)
TestRunner::Cmd("wine")                              // local exec via prefix command

Cmd(cmd) is a generic <cmd> <bin> <args> prefix runner — covers wine, qemu-user, valgrind, gdbserver, anything with that shape. Probes via which <cmd>.

For elaborate setups (rsync, ssh ControlMaster, env vars on the spawn, QEMU_LD_PREFIX for sysroots), construct TestRunner directly — copy/exec/cleanup/probe are public string fields with {bundle}, {remote_bundle}, {bin}, {bin_name}, {args} placeholders.

For cross-arch builds, set cfg.sysroot on the Configuration to point at a sysroot for the target. BuildStdPcm and the compile/link commands both consume it: --sysroot=<path> is passed to clang, and the std module is precompiled against the sysroot's libc++ headers. Ordinary compiles are pointed at the same headers (-nostdinc++ -isystem <sysroot>/usr/include/c++/v1), so a unit that #includes a standard header gets the sysroot's libc++ and not the host toolchain's. The module source has to come from the same libc++ release as those headers, so it is taken from <sysroot>/usr/share/libc++/v1/std.cppm when the sysroot ships it, else from the toolchain when both are the same major release, else from the sources crafter-build carries for other releases (share/crafter-build/libc++-modules/<major>/, crafter-build --version lists them). Alpine is the common case for the last two: its libc++-dev has the headers and no module source. When nothing matches, the build stops with one line naming both releases, installing that release's share/libc++/v1 directory into the sysroot resolves it. The cheapest aarch64 sysroot is an extracted Arch Linux ARM rootfs plus libc++ + libc++abi + gcc installed into it via pacman --root <rootfs> --config <alarm-pacman.conf> --dbpath <rootfs>/var/lib/pacman -Sy … (point pacman at ALARM's mirrors via explicit config to avoid pulling host-arch packages).

For --target=x86_64-w64-mingw32 (Windows from Linux), the pipeline cross-compiles as long as mingw-w64 is installed, with libstdc++ 15 or newer for its std module. clang finds it by the x86_64-w64-mingw32-gcc on PATH; CRAFTER_MINGW_DIR names another prefix (the directory holding x86_64-w64-mingw32/ and lib/gcc/), and inside the Flatpak the host's /usr is used when it has mingw-w64. Without one the build stops with a message saying where it looked. The prefix is clang's sysroot as it is, so Windows libraries installed into its include/ and lib/ are found, unless it also holds a Linux system: the host's /usr in the Flatpak, or any prefix whose include/ has a C library's features.h, as /usr does. clang searches a sysroot's include/ and lib/, and in such a prefix those hold glibc's headers and Linux libraries, so clang is shown only its x86_64-w64-mingw32/, lib/gcc/ and lib64/gcc/, as links in mingw-sysroot/ in the cache (~/.cache/crafter.build/, in the Flatpak ~/.var/app/net.catcrafts.CrafterBuild/cache/crafter.build/, or $XDG_RUNTIME_DIR/crafter.build/ when the cache's filesystem takes no symbolic links). Compiler messages still name those headers by their paths in the prefix. Pair it with --runner=cmd:wine to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. -fuse-ld=lld is auto-injected on every link, and -lstdc++exp is auto-linked for the mingw target so user projects don't need to declare those flags.

For --target=wasm32-wasip1, the WASI sysroot is the one beside the toolchain (the Flatpak bundles one) unless CRAFTER_BUILD_WASI_SYSROOT names another, and tests run under wasmtime. C++ exceptions work as on the other targets: every unit and the std module are compiled with -fwasm-exceptions in the standardized form of WebAssembly exception handling (exnref), against the exception-enabled libc++ in the sysroot's lib/<triple>/eh/, and -lunwind is linked automatically. A sysroot without that libc++ (wasi-sdk before 33) stops the build with one line saying so. The result runs on engines with that proposal: Chrome 137, Firefox 131 and Safari 18.4 or newer, and the wasmtime the Flatpak bundles. A page from EnableWasiBrowserRuntime checks first and names what an older browser lacks in the console, instead of failing to compile the module. An exception that escapes main leaves the program as an uncaught WebAssembly exception (wasmtime reports thrown Wasm exception and exits 1, a page gets a WebAssembly.Exception) without calling std::terminate, so a std::set_terminate handler does not run and nothing prints the exception's type or what(): wasm exception handling unwinds in a single phase, and nothing finds out that no handler is left until the stack is gone. Catch it in main to report it.

A wasm build refuses four things before it starts, each with a message that says why: -flto in compileFlags or linkFlags (LTO code generation drops the exception handling, WebAssembly/wasi-sdk#629), -fno-exceptions (the std module is built with exceptions, and a unit without them cannot import it), a shared library (the exception-enabled libc++ is static archives only) and packaging as a Flatpak (a wasm build stays a .wasm; see Flatpak output). setjmp and longjmp work in C and C++ sources, with -lsetjmp linked automatically like -lunwind; a longjmp across a noexcept function ends the program, because it is a wasm exception and the function's terminate handler catches it. Outside the Flatpak, a wasmtime older than 47 has exception handling off and needs -W exceptions=y, and a wasm-opt on PATH from a binaryen that cannot read the standardized encoding breaks release links, since clang runs it on optimized wasm links when it finds one.

In a page from EnableWasiBrowserRuntime, exit and _Exit end the program as they would anywhere else: none of its code runs on the way out, no destructor and no catch (...), its status is in window.crafter_wasi.exitCode, and bridges that call into it on their own are expected to stop. A program that hands the thread to the browser for good and goes on serving calls, as Crafter.Graphics's Window::StartSync() does, parks instead of exiting. Parking never returns, runs nothing of the program either, and leaves main's locals valid for the calls that follow:

extern "C" [[noreturn]] __attribute__((import_module("crafter_runtime"), import_name("park"))) void Park();

Configuring runners

Two layers, CLI wins over env, both override the per-test default of Local():

Env var (persistent, per shell or in CI):

export CRAFTER_BUILD_RUNNER_x86_64_w64_mingw32=cmd:wine
export CRAFTER_BUILD_RUNNER_aarch64_linux_gnu=cmd:qemu-aarch64
crafter-build test --target=x86_64-w64-mingw32           # uses cmd:wine

The variable name is CRAFTER_BUILD_RUNNER_<NORMALIZED_TARGET> (target triple with - and . replaced by _).

CLI (per invocation, scoped to --target=):

crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine

Spec grammar:

local
cmd:<command>                  # cmd:wine, cmd:qemu-aarch64, cmd:valgrind, ...

Each runner carries a probe command (e.g. which wine), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (AllPassed() returns true on skip-only runs).

Linking the parent project's library

A test fixture can depend on the project's own library so it can import and exercise its API:

// tests/UnitFoo/project.cpp
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view>) {
    Configuration cfg;
    cfg.path = "tests/UnitFoo/";
    cfg.name = "UnitFoo";
    cfg.outputName = "UnitFoo";
    cfg.type = ConfigurationType::Executable;
    cfg.dependencies = { ParentLib("MyLib") };       // <-- the magic line

    std::array<fs::path, 0> ifaces = {};
    std::array<fs::path, 1> impls = { "main" };
    cfg.GetInterfacesAndImplementations(ifaces, impls);
    return cfg;
}

ParentLib(name) walks the parent project's dependency graph (and the parent itself) to find a Configuration* by Configuration::name. The build links it into the test exe, so import MyLib; resolves naturally. See examples/tests/ for the complete worked example.

Linting & formatting

Lint rules are C++ in project.cpp with no .lintrc, no YAML, and no built-in rules. A rule is a named callback that runs once per source file, register it on the Configuration before returning:

cfg.AddLintRule("no-tabs", [](Crafter::LintContext& ctx) {
    if (ctx.Extension() != ".cpp" && ctx.Extension() != ".cppm") return;
    for (std::size_t n = 1; n <= ctx.lines.size(); ++n) {
        if (ctx.Line(n).contains('\t')) ctx.Report(n, "tab character (use spaces)");
    }
});

A rule that calls ctx.SetContent(newContent) is a transform which is defined once, it powers both verbs: lint reports where the transform would change the file (dry, never writes), and format applies it to disk:

cfg.AddLintRule("final-newline", [](Crafter::LintContext& ctx) {
    if (!ctx.content.empty() && !ctx.content.ends_with('\n')) {
        ctx.SetContent(ctx.content + '\n');
    }
});
crafter-build lint            # full dry gate: Report() findings + would-reformat, exit 1 on any
crafter-build lint 'spdx*'    # rule-name glob filter
crafter-build lint --list     # enumerate rules without running them
crafter-build format          # apply transforms, rewrite changed files in place (exit 0)
crafter-build format --check  # CI gate: list files that would change, exit 1 if any

Lint findings print compiler-style — file:line: warning: message [rule] — so editors and CI pick them up. format rewrites files in place (gofmt convention) and only touches files whose bytes actually change; report-only findings are lint's business and don't affect format's exit code. A project with no rules registered exits 1 with a message showing how to add one.

LintContext gives each rule:

Member Meaning
file absolute path of the file under lint
content the whole file
lines pre-split line views (report 1-based via Line(n))
Extension() file extension, e.g. ".cppm"
CommentStripped() content with comments and string/char literal bodies blanked to spaces — newlines kept, so line numbers stay valid (raw strings not recognized yet)
Report(line, msg) record a finding (line == 0 for whole-file)
SetContent(str) replace the file's content — makes the rule a transform, lines re-splits, CommentStripped() re-derives. Build the new string, call once at the end, don't assign content directly

Suppression is comment-based :

// lint-disable-next-line no-char-pointer      — one rule, the following line
// lint-disable-next-line naming, wrap-join    — several rules (space- or comma-separated)
// lint-disable-next-line                      — all rules, the following line
// lint-disable-file fixed-width-types         — one rule, whole file (any position)
// lint-disable-file                           — all rules, whole file

Scripts

A project has chores that are not part of building it: packaging, installing, publishing, generating documentation. A script gives one a name. Scripts are C++ in project.cpp like everything else, a name and a callback pushed onto cfg.scripts before returning the Configuration:

cfg.scripts.push_back({"docs", [](Crafter::ScriptContext& ctx) {
    return ctx.Run("python3 tools/gen-docs.py");
}});
crafter-build run                  # list the project's scripts
crafter-build run docs             # run one
crafter-build run docs --open api  # everything after the name is handed to the script

The callback returns the exit status, and crafter-build run exits with it. ctx.Run(command) runs a shell command with the terminal attached, so its output appears as it is produced and it can ask questions, and returns the command's exit code (128 plus the signal number when it was killed). A script with several steps stops at the first failure by returning that code:

cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) {
    const std::string dist = Crafter::ShellQuote((ctx.projectDir / "dist").string());
    if (const std::int32_t code = ctx.Run(std::format("mkdir -p {}", dist)); code != 0) return code;
    return ctx.Run(std::format("tar -czf {}/myapp.tar.gz -C {} .", dist, Crafter::ShellQuote(ctx.project.ProgramDir().string())));
}});

ScriptContext gives each script:

Member Meaning
project the Configuration the script is declared on: the one project.cpp returned, or of several the one whose scripts holds it. Read the project through this rather than through a cfg captured by reference
projectDir absolute directory of the project file
args everything typed after the script's name, untouched
Run(command) run a shell command with the terminal attached and return its exit code

Things to know:

  • Everything after the script's name belongs to the script, including what looks like an option of crafter-build (--help, -v). Options and project args for crafter-build go before the name: crafter-build --debug run package.
  • run loads project.cpp but does not build the project. A script that needs the build output runs after crafter-build.
  • Commands run in the directory crafter-build was started from. Build paths from ctx.projectDir, and quote anything that is not a literal with Crafter::ShellQuote.
  • Only the scripts of the project you run crafter-build in are available. A dependency's scripts are not.
  • Inside the Flatpak, commands run in its sandbox: the host's files are visible, but the tools on PATH are the ones the Flatpak ships (git, cmake, python3, tar, ...), not everything installed on the host.
  • A return value outside 0 to 255 is not an exit status and becomes 1. So does a script that throws, with the exception's message printed.

Debugging

Programs that -r and the test runner start run inside the Flatpak's sandbox, and so do the tools to debug them: lldb, with lldb-server, lldb-dap and lldb-mcp, from the same LLVM build as the compiler; gdb, gdbserver, valgrind and strace from the Freedesktop Sdk; the Khronos Vulkan validation layer; and the SPIRV-Tools programs (spirv-val, spirv-opt, spirv-dis, ...). A default build is optimised (-O3, and ThinLTO except for wasm) and carries no debug information: set cfg.debug = true for a program you want to debug, which compiles its C++ units with -g and links it without LTO; its C and CUDA sources (cfg.cFiles, cfg.cuda) stay at -O3 without debug information. A project.cpp that calls ApplyStandardArgs sets it from the --debug argument, as in crafter-build --debug -r. Start the tools with --command:

flatpak run --die-with-parent --command=lldb net.catcrafts.CrafterBuild ./bin/myapp-<variant>/myapp
flatpak run --die-with-parent --command=valgrind net.catcrafts.CrafterBuild ./bin/myapp-<variant>/myapp

Every flatpak run is a sandbox of its own, with process IDs of its own, so a debugger in one cannot see a program that another one, such as crafter-build -r, started. Either start the program under the debugger, or run the debugger inside that program's sandbox with flatpak enter, giving the instance flatpak ps lists for net.catcrafts.CrafterBuild and the debugger's full path:

flatpak ps --columns=instance,application
flatpak enter <instance> /app/bin/lldb -n myapp

Where /proc/sys/kernel/yama/ptrace_scope is 1, a debugger in the sandbox, where processes hold no capabilities, can attach to a program that is not its descendant only when the program allowed it with prctl(PR_SET_PTRACER, …): with the debugger's process ID, or with PR_SET_PTRACER_ANY for any process. Otherwise the attach fails. A program started under the debugger is its descendant. Prefer flatpak enter to lldb-server gdbserver in one sandbox and lldb's gdb-remote from another: when a process in lldb's own sandbox has the remote program's process ID, lldb takes that process's executable for the program's: symbols come out wrong, and a breakpoint in the program's source finds no location.

The validation layer is enabled the usual ways, by the program itself or from the environment: flatpak run passes VK_INSTANCE_LAYERS, VK_LOADER_LAYERS_ENABLE and the layer's VK_KHRONOS_VALIDATION_* settings into the sandbox. VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 adds GPU-assisted validation (GPU-AV):

VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 crafter-build -r

The layer is the Vulkan SDK release of the runtime's own Vulkan loader. VK_LAYER_PATH and VK_ADD_LAYER_PATH are cleared on the way into the sandbox, so a layer installed on the host is out of reach.

Examples

examples/ contains progressively larger self-contained projects:

Example Shows
hello-world Smallest possible project: project.cpp + main.cpp
with-module Adding a C++ module interface
library Library + executable, linked via cfg.dependencies
tests tests linking the parent library

Each builds standalone: cd examples/<name> && crafter-build.

License

This project is licensed under the GNU Lesser General Public License, version 3 only (LGPL-3.0-only). See LICENSE for the license text. The LGPL supplements the GNU General Public License version 3, a copy of which is included as LICENSE.GPL.

The example code under examples/ is licensed under the MIT license (see examples/LICENSE), so it can be freely copied into your own projects.

The lib/ directory contains vendored third-party code (nlohmann/json, glslang's DirStackFileIncluder) that remains under its own permissive licenses, see the headers of those files.

Copyright (C) 2026 Catcrafts® catcrafts.net