Effective Clean Target Patterns
Learn different patterns for clean targets in Makefiles: basic clean, distclean, mostlyclean, and maintainer-clean following GNU conventions.
Build Patterns
Detailed Explanation
Clean Targets Done Right
A good clean target is essential. GNU coding standards define four levels of cleaning, each progressively removing more files.
The Four Clean Levels
.PHONY: mostlyclean clean distclean maintainer-clean
mostlyclean:
rm -f $(OBJS) $(DEPS)
clean: mostlyclean
rm -f $(TARGET)
distclean: clean
rm -f config.mk .config
rm -rf build/
maintainer-clean: distclean
rm -f configure aclocal.m4
rm -rf autom4te.cache/
@echo "This command is intended for maintainers only."
- mostlyclean: Remove intermediate files (object files, dependency files) but keep the final binary. Useful during development when you want a partial rebuild.
- clean: Remove everything that
makebuilt, including the final binary. - distclean: Remove everything not in the source distribution — configuration files, build directories.
- maintainer-clean: Remove everything that can be regenerated, including autoconf-generated files. Used only by package maintainers.
Progressive Cleaning
Each level depends on the previous one, forming a chain: maintainer-clean -> distclean -> clean -> mostlyclean. This avoids duplicating rm commands.
Language-Specific Clean Patterns
C/C++:
clean:
rm -f $(OBJS) $(DEPS) $(TARGET)
rm -rf *.dSYM
Python:
clean:
rm -rf __pycache__ .pytest_cache .mypy_cache htmlcov *.egg-info dist build
find . -name '*.pyc' -delete
find . -type d -name '__pycache__' -exec rm -rf {} +
Node.js:
clean:
rm -rf node_modules dist .next .cache .parcel-cache coverage
Safety Tips
- Never use
rm -rf /orrm -rf *— always use specific paths - Use variables for directory names so they match build targets
- Add
@echowarnings before destructive operations - Consider a
clean-drytarget that lists what would be deleted without actually deleting
Use Case
Implementing a thorough and safe cleanup system for a project with multiple build artifacts, generated files, and cached data that need different levels of cleaning.