开发者

How to include clean target in Makefile?

开发者 https://www.devze.com 2022-12-26 14:25 出处:网络
I have a Makefile that looks like this CXX = g++ -O2 -Wall all: code1 code2 code1: code1.cc utilities.cc

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 s开发者_StackOverflowo 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 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.


In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2


By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done
0

精彩评论

暂无评论...
验证码 换一张
取 消