fix(build): name a source's object from its path

The object of an implementation unit was named from its file's name
alone, <build dir>/<name>_impl.o, and that of a C or CUDA source
likewise, <name>_source.o. Two sources of one configuration with the
same file name in different directories were therefore compiled into
one object, each over the other, with one dependency file between
them, and the link was given that object twice (issue #50). A build of
an a/Thing.cpp and a b/Thing.cpp that each define a function failed at
the link, with duplicate symbols of one of the two and no word of the
other. A debug build of two such files that define nothing another
file names succeeded, and its program had one file's code twice and
the other's not at all. A .c and a .cu of one name shared an object in
one directory as well.

An object, with its dependency file beside it, is now named from where
its source lies: under <build dir>/objects by the source's path from
the configuration's directory, objects/a/Thing_impl.o for a/Thing.cpp,
or, for a source outside that directory, under
<build dir>/objects-outside by its whole path. A .cu's object ends in
_cuda.o; a .cpp's still ends in _impl.o and a .c's in _source.o. Two
sources then have one object only when their paths are one once . and
.. are taken out of them: any other two differ by path or by ending in
one of the two directories, and the two directories share nothing,
whatever a project calls its own directories. They are directories of
their own, and not the build directory itself, because that one holds
files named after other things: an interface unit's object, the record
of the link and the list of its objects and, for an executable, the
BMIs.

ObjectPath gives that name, exported beside ExpectedOutput for what
looks at an object from outside Build(). Build() names each object by
the same rule, once, as it goes over the sources, and the list it
keeps of them for the link is what the check whether an object is
newer than the output reads as well. Before, each put the name
together for itself: Implementation::Check, Implementation::Schedule,
and Build() where it compiles C and CUDA sources, lists the link's
objects and checks whether to link again. Implementation::Check and
Schedule are given the object, where they put its name together from
the build directory. The job that compiles a source makes the
directory of its object first, since the compiler makes none. The C
compile quotes its source, dependency file and object for the shell,
as the CUDA compile does: the object of a source outside the
configuration's directory holds that source's whole path, and so
directories the command did not name before, the working directory's
among them where the source is listed relative to it.

The progress line of the compile of a .cpp, .c or .cu names the source
by the path its object is named from, "Compiling a/Thing.cpp" where it
was "Compiling Thing.cpp" for both, and so does the error for a .cu
without an nvcc.

What else changes: every implementation unit and every C and CUDA
source has its object in a new place, so an existing build directory
compiles them once more. The objects under the old names stay where
they are, unused; a static library's archive does not keep them, being
written anew. Interface units are as they were: a BMI is found by its
module's name, so two interface files of one name would have to be one
module. A source that a configuration lists twice is also as it was,
compiled twice into its one object, which the link is given twice.

In IncrementalHeaderChange, IncrementalInterfaceChange, StdPcmRebuild
and TransitiveInterfaceChange, the lines that spelled out an object's
old name take it from ObjectPath.

Fixes #50
This commit is contained in:
Jorijn van der Graaf 2026-11-19 11:02:39 +01:00
commit 7f8089474b
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
8 changed files with 162 additions and 70 deletions

View file

@ -320,6 +320,73 @@ fs::path Crafter::ExpectedOutput(const Configuration& config) {
return mingwTarget ? dir / std::format("{}.dll", config.outputName) : dir / std::format("lib{}.so", config.outputName);
}
namespace {
// `path` resolved against the working directory, with no `.` or `..` in
// it and no separator at its end.
fs::path WithoutSeparator(fs::path path) {
path = fs::absolute(path).lexically_normal();
return path.has_filename() ? path : path.parent_path();
}
// What the name of a source's object ends in, by the source's
// extension: one ending for each kind of source, so a .c beside a .cu
// of its name has an object of its own. Empty for an extension Build()
// compiles no source of.
std::string_view ObjectSuffix(std::string_view extension) {
if (extension == ".cpp") return "_impl.o";
if (extension == ".c") return "_source.o";
if (extension == ".cu") return "_cuda.o";
return "";
}
// ObjectPath's rule for the sources of one configuration, with what it
// takes from the configuration worked out once for all of them.
class SourceLayout {
public:
SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside") {}
// The object of the source a configuration lists as `listed`, which
// is its path without its extension, `extension`.
fs::path Object(const fs::path& listed, std::string_view extension) const {
fs::path object = fs::absolute(listed).lexically_normal();
object += ObjectSuffix(extension);
const fs::path within = Within(object);
return within.empty() ? outside / object.relative_path() : inside / within;
}
// That source as the progress line of its compile names it: by its
// path from the configuration's directory, or by its whole path
// when it lies outside that directory.
std::string Shown(const fs::path& listed, std::string_view extension) const {
fs::path source = fs::absolute(listed).lexically_normal();
source += extension;
const fs::path within = Within(source);
return within.empty() ? source.string() : within.string();
}
private:
// The path of `resolved` from the configuration's directory; empty
// when it does not lie in that directory.
fs::path Within(const fs::path& resolved) const {
const fs::path relative = resolved.lexically_relative(directory);
if (relative.empty() || relative == "." || *relative.begin() == "..") return {};
return relative;
}
fs::path directory;
fs::path inside;
fs::path outside;
};
}
fs::path Crafter::ObjectPath(const Configuration& config, const fs::path& source) {
const std::string extension = source.extension().string();
if (ObjectSuffix(extension).empty()) throw std::invalid_argument(std::format("{} is not a .cpp, .c or .cu source", source.string()));
fs::path listed = source;
listed.replace_extension();
return SourceLayout(config.path, config.BuildDir()).Object(listed, extension);
}
CompileCommand Crafter::GetCompileCommand(const Configuration& config) {
CompileCommand out;
out.stdPcmDir = StdPcmDir(config);
@ -884,6 +951,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
}
fs::path buildDir = config.BuildDir();
// Where the object of each .cpp, .c and .cu of this configuration goes,
// and what its compile is called (ObjectPath).
const SourceLayout layout(config.path, buildDir);
// Everything this configuration produces lands here: a library's archive
// and module PCMs, an executable and the files it reads at run time.
fs::path outputDir = config.ProgramDir();
@ -893,13 +963,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// follows outputDir in it, or, for a directory copied into outputDir
// itself ("data/", "data/."), the names of what that directory holds.
std::set<std::string> placed = {ExpectedOutput(config).filename().string()};
const auto withoutSeparator = [](fs::path path) {
path = fs::absolute(path).lexically_normal();
return path.has_filename() ? path : path.parent_path();
};
const fs::path outputRoot = withoutSeparator(outputDir);
const fs::path outputRoot = WithoutSeparator(outputDir);
const auto place = [&](const fs::path& destination, const fs::path& source) {
const fs::path normal = withoutSeparator(destination);
const fs::path normal = WithoutSeparator(destination);
if (normal != outputRoot) {
placed.insert(normal.lexically_relative(outputRoot).begin()->string());
return;
@ -1222,22 +1288,36 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
cArchFlags += WasmCompileFlags(config);
}
for (const fs::path& cFile : config.cFiles) {
const std::string objPath = std::format("{}_source.o", (buildDir / cFile.filename()).string());
objects.emplace_back(objPath);
const fs::path object = layout.Object(cFile, ".c");
objects.push_back(object);
const std::string objPath = object.string();
const std::string srcPath = std::format("{}.c", cFile.string());
// C sources carry their dependencies entirely in #includes, so the
// depfile the compile below writes is the whole record of what this
// object was built from beyond the .c itself.
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) {
jobs.Add(std::format("Compiling {}.c", cFile.filename().string()), [command = std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())] {
// The job makes the directory of its object, which is one for
// the source's own directory: the compiler makes none.
//
// The source, the dependency file and the object are quoted
// for the shell, as the CUDA compile below quotes its own. The
// object of a source outside the configuration's directory is
// named by that source's whole path, and so holds directories
// this command did not name while an object lay in the build
// directory itself: the working directory's, where the source
// is listed relative to it. A build from a directory with a
// space in its name would have stopped here.
jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".c")), [directory = object.parent_path(), command = std::format("{8} {0} --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7} -o {9}", ShellQuote(srcPath), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, ShellQuote(std::format("{}.d", objPath)), GetToolchain().clang.string(), ShellQuote(objPath))] {
fs::create_directories(directory);
return RunBuildCommand(command);
});
}
}
for (const fs::path& cFile : config.cuda) {
const std::string objPath = std::format("{}_source.o", (buildDir / cFile.filename()).string());
objects.emplace_back(objPath);
const fs::path object = layout.Object(cFile, ".cu");
objects.push_back(object);
const std::string objPath = object.string();
const std::string srcPath = std::format("{}.cu", cFile.string());
// nvcc writes the depfile clang writes for a C source (-MD -MF): the
// .cu and every header it read, the toolkit's and the system's among
@ -1249,10 +1329,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) {
const Toolchain& toolchain = GetToolchain();
if (toolchain.nvcc.empty()) {
jobs.Fail(std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError));
jobs.Fail(std::format("cannot compile {}: {}", layout.Shown(cFile, ".cu"), toolchain.nvccError));
break;
}
jobs.Add(std::format("Compiling {}.cu", cFile.filename().string()), [command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] {
jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".cu")), [directory = object.parent_path(), command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] {
fs::create_directories(directory);
return RunBuildCommand(command);
});
}
@ -1424,11 +1505,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
}
for(Implementation& implementation : config.implementations) {
if(implementation.Check(buildDir, pcmDir, externalFloor)) {
const fs::path object = layout.Object(implementation.path, ".cpp");
if(implementation.Check(object, pcmDir, externalFloor)) {
buildResult.repack = true;
implementation.Schedule(jobs, command, pcmDir, buildDir);
implementation.Schedule(jobs, command, pcmDir, buildDir, object, layout.Shown(implementation.path, ".cpp"));
}
objects.push_back(buildDir / std::format("{}_impl.o", implementation.path.filename().string()));
objects.push_back(object);
}
if (std::string failed = jobs.Wait(); !failed.empty()) {
@ -1524,48 +1606,20 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// after compile but before link): on the next run the .cpp is
// already ≤ .o so Implementation/Module Check returns false and
// nothing else would notice the archive is stale.
//
// Every object of the step is looked at, by the name the step
// itself is given. C and CUDA objects are archive members too,
// and their compile loop above is the only thing that knows it
// rebuilt one — it sets no repack flag, so without this a .c
// edit recompiled the object and then linked nothing.
if (!buildResult.repack) {
auto objNewer = [&](const fs::path& obj) {
for (const fs::path& object : objects) {
std::error_code ec;
auto t = fs::last_write_time(obj, ec);
return !ec && t > consumerMtime;
};
for (const std::unique_ptr<Module>& iface : config.interfaces) {
if (objNewer(buildDir / std::format("{}.o", iface->path.filename().string()))) {
const fs::file_time_type written = fs::last_write_time(object, ec);
if (!ec && written > consumerMtime) {
buildResult.repack = true;
break;
}
bool partHit = false;
for (const std::unique_ptr<ModulePartition>& part : iface->partitions) {
if (objNewer(buildDir / std::format("{}.o", part->path.filename().string()))) {
partHit = true;
break;
}
}
if (partHit) { buildResult.repack = true; break; }
}
if (!buildResult.repack) {
for (const Implementation& impl : config.implementations) {
if (objNewer(buildDir / std::format("{}_impl.o", impl.path.filename().string()))) {
buildResult.repack = true;
break;
}
}
}
// C and CUDA objects are archive members too, and their compile
// loop above is the only thing that knows it rebuilt one — it
// sets no repack flag, so without this a .c edit recompiled the
// object and then linked nothing.
if (!buildResult.repack) {
auto sourceObjNewer = [&](const std::vector<fs::path>& sources) {
for (const fs::path& source : sources) {
if (objNewer(buildDir / std::format("{}_source.o", source.filename().string()))) return true;
}
return false;
};
if (sourceObjNewer(config.cFiles) || sourceObjNewer(config.cuda)) {
buildResult.repack = true;
}
}
}
}

View file

@ -13,8 +13,8 @@ namespace Crafter {
Implementation::Implementation(fs::path&& path) : path(std::move(path)) {
}
bool Implementation::Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor) const {
std::string objPath = std::format("{}_impl.o", (buildDir/path.filename()).string());
bool Implementation::Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor) const {
std::string objPath = object.string();
std::string cppPath = std::format("{}.cpp", path.string());
// The depfile clang wrote beside the object lists the headers this TU
// included; nothing else in the configuration knows about them, since
@ -36,7 +36,7 @@ namespace Crafter {
}
return false;
}
void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const {
void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const {
std::vector<JobGroup::Job> after;
for(ModulePartition* dependency : partitionDependencies) {
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
@ -50,7 +50,11 @@ namespace Crafter {
// module rebuilt in place, for a mingw-w64 or libc++ update under
// the same compiler, left the objects importing it as they were, and
// the next build only relinked them.
jobs.Add(std::format("Compiling {}.cpp", path.filename().string()), [command = std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())] {
//
// The job makes the directory of its object, which is one for the
// source's own directory (ObjectPath): the compiler makes none.
jobs.Add(std::format("Compiling {}", shown), [directory = object.parent_path(), command = std::format("{0} {1}.cpp -c -MD -MF {2}.d -fmodule-file-deps -o {2}", clang, path.string(), object.string())] {
fs::create_directories(directory);
return RunBuildCommand(command);
}, after);
}

View file

@ -804,6 +804,36 @@ export namespace Crafter {
// disagree about the file name.
fs::path ExpectedOutput(const Configuration& config);
// Where Build leaves the object of `source`, one of this Configuration's
// implementation units (.cpp), C sources (.c) or CUDA sources (.cu),
// given with its extension; a relative `source` is taken against the
// working directory, as Build takes cFiles and cuda. The dependency file
// the compiler writes lies beside it, as <object>.d.
//
// The object is named from where the source lies: under
// BuildDir()/objects by the source's path from the Configuration's
// `path`, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source
// outside that directory, under BuildDir()/objects-outside by its whole
// path. The name ends in _impl.o for a .cpp, _source.o for a .c and
// _cuda.o for a .cu. So two sources have one object only when their
// paths are one once `.` and `..` are taken out of them as they are
// written: any other two differ by path or by ending in one of the two
// directories, and the two directories share nothing.
//
// Objects were named from the file name alone, in BuildDir() itself:
// a/Thing.cpp and b/Thing.cpp were both compiled into Thing_impl.o,
// each over the other, and the link was given that object twice. The
// link then failed, or, in a debug build of two sources that define
// nothing another file names, gave a program with one source's code
// twice and the other's not at all (issue #50).
//
// An interface unit's object is not named here. It lies in BuildDir()
// itself, named by the unit's file name alone, as its BMI is: clang
// looks a BMI up by its module's name, so two interface files of one
// name would have to be one module. Throws std::invalid_argument for a
// `source` with any other extension.
fs::path ObjectPath(const Configuration& config, const fs::path& source);
// `crafter-build install`: makes the Flatpak of the files/ `config` was
// built as (see Packaging::Flatpak), with its permissions, puts it into
// the project's repo, and installs it for this user from a user remote

View file

@ -19,10 +19,14 @@ namespace Crafter {
std::vector<std::string> pendingImports;
fs::path path;
Implementation(fs::path&& path);
bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const;
// Adds the job that compiles this unit to `jobs`, after the BMIs of
// the stale interface units it imports (ModulePartition::Schedule,
// Module::Schedule). For a unit Check found stale.
void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const;
// Whether `object`, the object Build() keeps for this unit
// (ObjectPath), has to be written again.
bool Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const;
// Adds the job that compiles this unit into `object` to `jobs`, after
// the BMIs of the stale interface units it imports
// (ModulePartition::Schedule, Module::Schedule), whose own objects go
// to `buildDir`. For a unit Check found stale. `shown` is the source
// as the job's progress line names it.
void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const;
};
}

View file

@ -111,9 +111,9 @@ int main() {
// source, and the consumer that imports the module.
fs::path interfacePcm = lib->PcmDir() / "Widget.pcm";
fs::path interfaceObject = lib->BuildDir() / "Widget.o";
fs::path libraryObject = lib->BuildDir() / "Widget_impl.o";
fs::path counterObject = lib->BuildDir() / "counter_source.o";
fs::path consumerObject = app.BuildDir() / "main_impl.o";
fs::path libraryObject = ObjectPath(*lib, staged / "lib" / "Widget.cpp");
fs::path counterObject = ObjectPath(*lib, staged / "lib" / "counter.c");
fs::path consumerObject = ObjectPath(app, staged / "main.cpp");
if (!BuildOk(app, "first pass")) {
std::println(std::cerr, "{} assertions failed", Failures);
@ -187,7 +187,7 @@ int main() {
// safe reading is "rebuild it once".
{
std::array<fs::file_time_type, 5> before = stamps();
fs::remove(lib->BuildDir() / "Widget_impl.o.d");
fs::remove(fs::path(libraryObject) += ".d");
if (BuildOk(app, "missing depfile pass")) {
std::array<fs::file_time_type, 5> after = stamps();
Check(after[2] > before[2], "an object whose dependency record is missing is rebuilt");

View file

@ -169,7 +169,7 @@ int main() {
std::unique_ptr<Configuration> lib = MakeLib(staged);
Configuration app = MakeConsumerScannedBeforeDependencies(staged, lib.get());
fs::path binary = app.BinDir() / "widget-app";
fs::path consumerObject = app.BuildDir() / "main_impl.o";
fs::path consumerObject = ObjectPath(app, staged / "main.cpp");
if (BuildOk(app, "first pass")) {
auto first = RunCommandWithTimeout(binary.string(), std::chrono::seconds(30));

View file

@ -57,7 +57,7 @@ int main() {
BuildResult built = BuildOnce(cfg);
Check(built.result.empty(), std::format("the project builds: {}", built.result));
const fs::path object = cfg.BuildDir() / "main_impl.o";
const fs::path object = ObjectPath(cfg, project / "main.cpp");
const fs::path stdPcm = StdPcmDir(cfg) / "std.pcm";
Check(fs::exists(object) && fs::exists(stdPcm), std::format("{} and {} exist", object.string(), stdPcm.string()));
if (!fs::exists(object) || !fs::exists(stdPcm)) return 1;

View file

@ -206,8 +206,8 @@ int main() {
fs::path binary = app.BinDir() / "consumer";
fs::path widgetInterfaceObject = widget->BuildDir() / "Widget.o";
fs::path widgetImplObject = widget->BuildDir() / "Widget_impl.o";
fs::path consumerObject = app.BuildDir() / "main_impl.o";
fs::path widgetImplObject = ObjectPath(*widget, staged / "widget" / "Widget.cpp");
fs::path consumerObject = ObjectPath(app, staged / "main.cpp");
if (BuildOk(app, "first pass")) {
CheckAgrees(binary, "first pass");