为何我的Makefile未自动删除中间文件?如何配置自动清理?
The Root Cause
GNU Make only automatically cleans up intermediate files created by implicit rules (like the default logic for compiling .c to .o files). In your explicit plotsource rule, files like xac, heapsort, etc., are generated directly via shell commands—Make doesn’t recognize them as temporary intermediate files unless you explicitly tell it to. That’s why they stick around after your build finishes.
Fix 1: Use the .INTERMEDIATE Special Target
This is the cleanest, most "Make-native" way to handle temporary files. Add a .INTERMEDIATE target listing all your intermediate files, and Make will automatically delete them once they’re no longer needed for building the final target (plotsource):
.INTERMEDIATE: xac xab xaa heapsort downheat upheat plotsource: memo.md split memo.md -l8 cat xac | awk '/[0-9].*/{print $$1" "$$6}' > heapsort cat xab | awk '/[0-9].*/{print $$1" "$$6}' > downheat cat xaa | awk '/[0-9].*/{print $$1" "$$6}' > upheat join upheat downheat | join - heapsort > plotsource
Fix 2: Explicitly Delete Files in the Rule
If you prefer a more hands-on approach, you can add a final shell command to delete the intermediate files using $(RM) (Make’s built-in variable for rm -f, which is safer than raw rm):
plotsource: memo.md split memo.md -l8 cat xac | awk '/[0-9].*/{print $$1" "$$6}' > heapsort cat xab | awk '/[0-9].*/{print $$1" "$$6}' > downheat cat xaa | awk '/[0-9].*/{print $$1" "$$6}' > upheat join upheat downheat | join - heapsort > plotsource $(RM) xac xab xaa heapsort downheat upheat
Note: The downside here is that if any command before the final $(RM) fails, the cleanup won’t run. The .INTERMEDIATE method is more reliable because Make handles cleanup even if some steps fail (as long as the final target is successfully built).
Bonus: Simplify Your Rule (Optional)
While not directly related to cleanup, you can streamline your rule to avoid creating some intermediate files entirely using pipes, which reduces clutter and potential cleanup issues:
.INTERMEDIATE: xac xab xaa plotsource: memo.md split memo.md -l8 # Skip intermediate file writes with process substitution (bash/zsh only) join <(awk '/[0-9].*/{print $$1" "$$6}' xaa) <(awk '/[0-9].*/{print $$1" "$$6}' xab) | join - <(awk '/[0-9].*/{print $$1" "$$6}' xac) > plotsource
内容的提问来源于stack exchange,提问作者Yuki Ito

