Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include clean target in Makefile?

Tags:

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?

like image 937
neversaint Avatar asked Apr 14 '10 07:04

neversaint


People also ask

How do you make a clean target in makefile?

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.

What is in makefile target?

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.


1 Answers

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.

like image 105
unwind Avatar answered Oct 18 '22 17:10

unwind