You rebuild every library or object file by deleting the build system's intermediate output—object files, static and shared libraries, and generated dependency metadata—and then re-running the build from a verified clean configuration. The key condition: remove generated artifacts while leaving source files, checked-in configuration, and anything installed system-wide untouched. "Every" usually means every artifact your build system produced, not every .o or .a file on disk; wiping preinstalled system libraries can break your toolchain and is almost never what you want. The exact deletion target depends on your build system, and that's where most mistakes happen.
This guide walks through the mechanics: why stale artifacts cause phantom failures, how to identify what's actually generated, step-by-step procedures for the common build systems (Make, CMake plus Make or Ninja, Autotools, Meson, Bazel, Cargo, and IDE-managed projects), how to verify success, and the traps that turn a routine clean into hours of debugging.
Why a stale artifact can survive a rebuild
A build system decides what to recompile by comparing timestamps and, in more modern tools, content hashes. Object files and libraries are caches. When the cache and reality disagree—a header changed but the dependency file didn't notice, a compiler flag changed without touching sources, a .a archive still contains an old member—the build silently links stale code.
A classic example: you edit a struct in a header included by foo.c. If foo.d (the generated dependency file) is missing or corrupted, Make sees an "up-to-date" foo.o with a newer timestamp than the header and skips recompilation. Later, bar.o was compiled against the new layout, and the two objects disagree about struct size. You get a segfault or garbage output that vanishes whenever you delete one file. That's the signature of a stale object.
Libraries add a second layer. A .a static archive is a container of object files; if its creation rule depends on a member list that's out of date, the archive can retain a removed member. Shared libraries (.so/.dylib/.dll) can be stale relative to their sources, or a stale one may be picked up at runtime via a search path. Rebuilding every object file is the reliable reset when you can't tell which layer is stale.
The cost is time, not correctness risk—provided you delete only generated files. That distinction drives the entire procedure.
Prerequisites before you delete anything
Before touching any files, confirm four things.
1: Version control is clean or committed. Run git status (or your VCS equivalent). You want a known-good point to return to. Uncommitted source changes are safe from a clean—clean removes outputs, not sources—but committing first makes recovery trivial. 2: You know the build directory. In-source builds scatter output among sources; out-of-source builds keep it all under one directory (often build/). Know which you have. 3: You know how to configure the project. A clean rebuild usually requires a configure/regenerate step. Keep the original configure command or the notes for it, including any options like -DCMAKE_BUILD_TYPE=Release or --enable-feature. Losing these is the most common cause of a "successful" rebuild that produces different binaries. 4: You have build dependencies installed. A rebuild reruns the compiler, headers, and third-party libraries. If the environment changed since the last build, expect configure-time errors—and note that a clean will surface them rather than hide them, which is the point.
Check success criterion for this stage: you can state the exact configure command and the exact directory that holds build output. If you can't, find that out first.
Step 1: Identify what is generated versus what is source
Deletion is irreversible in practice (regenerating isn't always byte-identical). Inventory before you remove.
Generated categories in a typical C/C++ project:
Object files: *.o, *.obj Static libraries: *.a, *.lib Shared libraries and import libs: *.so, .so., *.dylib, *.dll, *.dll.a Dependency files: *.d, *.d, plus *.P or *.Tpo variants from Autotools Generated sources: files produced by code generators, often under build/generated or listed in a .gitignore Build metadata: .deps/, autom4te.cache/, CMakeFiles/, CMakeCache.txt, *.ninja_deps, *.ninja_log Linker/compiler response files and compile_commands.json Precompiled headers (.gch, .pch) and their caches
Never delete (generally):
Source files and checked-in headers CMakeLists.txt, Makefile.in, meson.build, configure.ac, and other project configuration .git/, .hg/, .svn/ System or package-manager-installed libraries under /usr/lib, /usr/local/lib, or your toolchain prefix
A practical identification method: run git ls-files and treat everything tracked as source; treat everything ignored and already present in the build tree as a candidate for removal. Cross-check with git clean -ndX (the -n makes it a dry run listing only ignored files, and -X limits it to ignored files). Dry-run output is your inventory. If your project isn't under version control, look for a .gitignore or MANIFEST to infer the intent, and when unsure, rename candidates to a backup directory rather than deleting them.
Watch for generated files that are tracked—some projects commit configure scripts or generated parsers. Deleting those without regenerating leaves you unable to build. The dry run and a quick git ls-files | grep for the candidate extension reveals them.
Step 2: Look for the build system's own clean target
Most build systems expose an official clean command that knows exactly what to remove. Prefer it over rm, because it won't overreach.
Make with a clean target: make clean. If the project also defines distclean or maintainer-clean (common in Autotools), those remove configuration output as well—useful when you want a from-scratch rebuild including ./configure. CMake: cmake --build build --target clean cleans the current build tree. It will not remove CMakeCache.txt or generated files it doesn't track; for that, delete the build directory (Step 3). Ninja: ninja -t clean cleans the target's known outputs; ninja -t clean -g additionally removes generated files marked as generators. Meson: ninja -C builddir clean (Meson drives Ninja). To fully reset, meson setup --wipe builddir re-creates the build directory from scratch. Autotools: make clean for objects; make distclean to also remove Makefiles and configure output. make maintainer-clean removes even more (regenerated configure, aclocal.m4)—use only if you have Autotools available to regenerate them. Bazel: bazel clean clears the output tree; bazel clean --expunge also removes the fetched external repositories and analyzer caches, forcing a full refetch. Prefer plain clean unless the cache itself is suspect. Cargo (Rust): cargo clean removes the target directory. Note that Cargo's incremental compilation cache lives there too, so a clean wipes it; cargo clean -p crate_name limits scope to one crate and its reverse dependencies.
A benchmark-style caveat: these targets differ in what they consider "the project." A repo containing multiple projects might have a top-level clean that only handles the top-level component. If make clean prints a short list of directories, confirm your component's directory appears; if not, clean it from within its own directory.
Success check: the clean command exits 0 and a subsequent find for object files under the build tree returns nothing (Step 5 shows the find command). If the clean target itself fails, jump to the troubleshooting section before proceeding—a failing clean often indicates a deeper problem, such as missing directories or permission errors.
Step 3: When no clean target exists or it's incomplete
Build systems without a clean target, or ones whose clean is partial, need direct removal. Keep deletion scoped to the build directory whenever possible.
Out-of-source build: the safest full clean is to remove the build directory entirely and reconfigure.
That sequence is CMake-specific, but the pattern holds for Meson (rm -rf builddir && meson setup builddir), Autotools out-of-tree (rm -rf build && mkdir build && cd build && ../configure), and hand-rolled Makefiles that accept an output prefix. Deleting the build directory is unambiguous: it can't miss a file, because there's nothing left.
In-source build: you can't delete the directory, so remove by pattern within the source tree, then verify with version control.
git clean -X removes only ignored paths, which in a well-configured repo is exactly the generated output. The -d adds untracked directories. If the dry run lists anything that isn't generated output—say, a .env or a local notes directory—either add a protective pattern or delete files individually. Never run git clean -xdf (lowercase x) on a source tree unless you truly want untracked non-ignored files gone too; that flag removes things the ignore rules were protecting.
For a project outside version control, delete by extension within the source root, then regenerate configuration:
If your shell is find from a non-GNU system, the ( ... ) grouping and -delete still work on BSD find, but test the command with -print instead of -delete first. Always preview.
One edge case worth naming: symlinked build outputs. Some projects symlink libfoo.so to libfoo.so.1.2.3. Removing the versioned file leaves a dangling symlink that can confuse later linking steps; removing the symlink first avoids it. A pattern delete of *.so and then .so. handles both orders, but if you see ls -l showing broken links afterward, remove the links.
Step 3 success check: re-running the dry-run/dry-print command produces no output.
Step 4: Regenerate configuration, then build
Deleting objects isn't a rebuild; running the build is. For most projects the sequence is: (1) regenerate build metadata if you removed it, (2) compile, (3) link, (4) optionally install to a staging prefix.
CMake/Ninja/Make: if the build directory survived and only objects were removed, cmake --build build or make -j recompiles what's missing. If the build directory was removed, re-run cmake -S . -B build (the configure step) before building. Autotools: if you ran make distclean, you must re-run ./configure (or ./autogen.sh && ./configure if configure was itself removed) before make. Meson: meson setup regenerates; --wipe handles the reconfigure automatically. Bazel/Cargo: the build command (bazel build //..., cargo build) regenerates everything internally; no separate configure step.
Two practical points. First, parallel builds (-j) expose missing dependencies that serial builds hide; if a clean parallel build fails with "No such file," suspect a missing order-only dependency rather than blaming the clean. Second, a full rebuild should take noticeably longer than an incremental one—if it finishes suspiciously fast, confirm it actually recompiled (Step 5) rather than trusting the absence of errors.
Success check for this stage: the build exits 0, links your executables and libraries, and the build log shows compiler invocations for your source files. If the build uses a response file or a wrapper script that suppresses output, check artifact timestamps instead.
Step 5: Verify the rebuild actually happened
Verification is cheap and catches the "clean succeeded, rebuild skipped" failure where a leftover timestamp or a misconfigured dependency made the build a no-op.
1: Timestamp check. Record the time, list object files, rebuild, list again. find build -name '*.o' -newermt '-10 minutes' should return a large set. If it returns nothing, nothing recompiled. 2: Content check by hashing. For the opposite failure—rebuilding but producing the old binary—compare sha256sum libfoo.so before and after; a change is expected if you changed sources, applied new flags, or upgraded a compiler. No change after a source edit means stale output got relinked. 3: Symbol check. If you suspect an old object snuck into a library, nm -C libfoo.a lists members' symbols; look for a symbol you deleted from source. Its presence indicates a stale member or a stale archive. ar t libfoo.a lists members by name if you know the filename. 4: Build-log check. Grep the log for each object filename; every expected object should appear. Then find for stray artifacts outside the build directory.
For in-source projects, git status after the rebuild should show only ignored-file changes, not tracked-file modifications that the build would have overwritten—if tracked files changed, the generator wrote into source paths and you may have a dirty-tree build that needs switching to out-of-source.
Build-system specifics and their traps
Make and hand-written Makefiles. The clean target is a convention, not a guarantee. Some Makefiles define clean as rm -f $(OBJS) but never remove the shared library or generated headers. Read the target's recipe (grep -A5 '^clean:' Makefile) before trusting it. Watch for clean also removing source fixtures under test/data—rare, but it happens when paths are wildcarded.
CMake. Deleting CMakeCache.txt without the rest of CMakeFiles/ leaves an inconsistent tree; delete the whole build directory instead. If your CMake project uses CMAKE_EXPORT_COMPILE_COMMANDS, the file vanishes with a build-directory delete—fine, unless an editor or static analysis tool depended on it; regenerate before running those tools.
Autotools. make distclean is the mainstream full clean, but it requires configure to exist and be executable. If a project ships configure and you delete it with an overzealous clean, you need autoreconf -fi (and the right Autotools versions) to recover. That recovery frequently fails on old projects with modern Autoconf—so confirm the checkout tracks configure before running any target that could remove it.
Bazel. bazel clean doesn't touch the external repository cache unless you add --expunge, and even then, the user-level Bazel cache (~/.cache/bazel) may hold relevant outputs. Also note that a clean invalidates the remote or disk cache keys only if inputs changed; a rebuild with --noremote_accept_cached is the way to force real re-execution when you're chasing a caching bug. Clearing the wrong Bazel cache can cost hours of refetching dependencies, so prefer the narrowest clean that resolves your symptom.
Meson. meson setup --wipe deletes the build directory's contents but preserves the command options from the previous configure, which avoids losing -D settings. That's a genuine advantage over rm -rf for reproducible rebuilds.
Cargo. cargo clean is safe but blunt; a full rebuild of a large workspace can be long, and incremental caches are lost. If you're debugging a specific crate, prefer cargo clean -p name. Note that proc-macro and build-script output caches under target/ go too, which is usually intended and occasionally the actual fix for confusing stale build-script behavior.
Xcode and other IDE projects. The "Clean Build Folder" command (Shift-Cmd-K in recent Xcode versions) removes the derived data for the project; "Clean" alone may leave module caches and precompiled headers. After exploiting the target's option, verify artifacts by locating the derived-data directory and confirming your build products have fresh timestamps. The equivalent virtualization applies to Visual Studio's "Clean Solution"/"Rebuild Solution," where "Rebuild" is effectively clean-then-build and is the reliable choice.
Cross-platform caveat: file extension assumptions differ. A .lib on Windows can be either a static library or an import library for a DLL; dumpbin /symbols or lib /list distinguishes them. On macOS, .a files are static archives like Linux, but framework bundles have a directory structure where deleting individual binaries without the bundle can leave broken references. When a delete target is a directory-like bundle, remove the whole bundle.
Troubleshooting: symptoms, likely causes, reversible checks
Symptom: build fails with missing headers that clearly exist. Likely cause: a generated header was deleted and its generator isn't wired into the build's default target. Check: look for the header's producing rule (grep for the filename in build files) and whether the rule runs by default. Reversible first step: re-run the original configure; in CMake, a fresh build directory often fixes generator wiring.
Symptom: "up to date" immediately after a clean. Likely cause: the clean didn't remove the objects the build system believes in—often a second build directory, a stale absolute cache path, or an overlay filesystem reporting odd times. Check: find . -name '*.o' across the entire project after cleaning. Reversible step: remove the build directory by path and reconfigure.
Symptom: link error for a symbol you know exists in source. Likely cause: a stale .a or .so elsewhere in the link line precedes the freshly built one, or the linker cache (ldconfig for system dirs) serves an old library. Check: print the resolved link line (make VERBOSE=1, cmake --build build --verbose) and note library order and paths. Reversible step: rename the suspected stale library aside and relink; if the error clears, the stale copy was the culprit.
Symptom: runtime picks up the wrong .so. Likely cause: LD_LIBRARY_PATH or the loader cache pointing at an old install. Check: ldd on Linux (or otool -L on macOS) shows the resolved path. Note the platform difference, then run with an explicit path in the environment.
Stop condition: if a clean build fails in a way that points at the toolchain or environment—linker crashes, missing standard headers, package-manager errors—further cleanup won't help. Restore the environment or escalate to whoever owns the build machine. Likewise, if deleting a build tree reveals that critical files were never in version control, stop rebuilding and recover from backup or a known-good reproduction before continuing.
Edge cases that change the "every" calculation
Submodules and vendored dependencies. A top-level clean may not recurse into third_party/ or git submodules. Those may have their own build directories that hold stale artifacts. Decide deliberately: cleaning vendored dependencies is often what you want after a cross-cutting change (like a compiler upgrade), but it can be expensive or even fail if the vendor project's build system is fragile. Document the decision so the next person doesn't wonder.
Shared caches and agent-scoped caches. Bazel, ccache, sccache, and distcc all hold compiled outputs outside your build tree. Deleting them is a separate, larger action. If your goal is "make sure nothing stale is being served," the relevant switch is to disable or bypass the cache for the verification build (for example, ccache with an empty cache directory or its disable environment variable, and ccache's documented environment variables for limiting cache hits). Avoid clearing a team-shared cache casually; on a shared CI host, an empty cache means everyone's next build is slower.
Docker images and container builds. "Every object file" inside a container build layer means a clean build context or --no-cache on the build step. Inherited caches (apt package caches, language package caches) are separate layers of stale risk; the rebuild won't clear them.
Installed copies. A rebuild updates the build tree, not the installed files under /usr/local or a prefix. If tests run against installed artifacts, reinstall after building (cmake --install build or make install), or point the tests at the build tree. Confusing installed and built copies is the most frequent post-clean confusion.
What you end up with, and what to keep
A correct full-rebuild procedure reduces to a short loop: identify generated output, let the build system clean what it owns, remove or delete the build directory for anything it doesn't, reconfigure with the recorded options, build, and verify with timestamps, hashes, and symbol lists. The failures worth remembering are the quiet ones—a clean target that misses the shared library, a clean that returns before deleting, a rebuild link that silently links an old archive because an install tree came first in the search path, and a project whose generated headers were tracked and lost. Each is detected by the verification step, which is why the procedure should end with proof that output was regenerated rather than with a successful exit code.
Keep three things for next time: the exact configure command with flags, the build system's clean-target semantics (what it does and doesn't remove), and the verification commands. Writing them into the project's build documentation or a short script pays back every time a stale-artifact mystery appears.