I have a Makefile that looks like this
CXX = g++ -O2 -Wall all: code1 code2 code1: code1.cc utilities.cc $(CXX) $^ -o $@ code2: code2.cc utilities.cc $(CXX) $^ -o $@
What I want to do next is to include clean target
so that every time I run make
it will automatically delete the existing binary files of code1
and code2
before creating the new ones.
I tried to put these lines at the very end of the makefile, but it doesn't work
clean: rm -f $@ echo Clean done
What's the right way to do it?
The Cleanup Rule clean: rm *.o prog3 This is an optional rule. It allows you to type 'make clean' at the command line to get rid of your object and executable files. Sometimes the compiler will link or compile files incorrectly and the only way to get a fresh start is to remove all the object and executable files.
A simple makefile consists of "rules" with the following shape: target ... : dependencies ... command ... ... A target is usually the name of a file that is generated by a program; examples of targets are executable or object files.
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean clean: rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With