tags:

views:

700

answers:

3

At work we use a common makefile that other makefiles include (via the include statement) and it has a generic "clean" target that kills some common files. I want to add on to that target in my new makefile so I can delete some specific files, but if I add a clean target in my makefile, it just overrides the old one.

I know I can just make a new target with a new name and have it call clean, and then do other stuff, but for sake of consistency I'd like to be able to just call make clean and have it do everything.

Is that possible?

A: 

It seems like the common makefile's rule should be called something like common-clean. Then each main makefile would declare their clean rule as

clean: common-clean

and you're set.

If that isn't an option, you could take a look at double colon rules, but those introduce a whole other set of issues to consider.

jamessan
+1  A: 

You can write your own clean and make it a preq of the common clean.

clean: myclean

myclean:
    rm whatever

Yours will run first. If for some reason you want the common clean to run first then the solution will be more complicated.

Beta
+2  A: 

I've seen this done at several shops. The most common approach is to use double-colon rules, assuming you're using something like GNU make. In your common makefile you would have something like this:

clean::
        # standard cleanup, like remove all .o's:
        rm -f *.o

Note that there are two colons following clean, not just one!

In your other makefile you just declare clean again, as a double-colon rule:

clean::
        # custom cleanup, like remove my special generated files:
        rm -f *.h.gen

When you invoke make clean, GNU make will automagically run both of these "branches" of the clean rule:

% make clean
rm -f *.o
rm -f *.h.gen

It's simple to set up and it composes quite neatly I think. Note that specifically because it is a double-colon rule, you don't get the "overriding commands" errors you normally get when you define two rules for the same target. That's sort of the point of double-colon rules.

Hope that helps,

Eric Melski
Electric Cloud, Inc.
http://blog.electric-cloud.com

Eric Melski
Thanks Eric, this works too, but I'd rather avoid modifying the common makefile if I can.
Paul D.
i was just looking for that and in my case the double-colon is the perfect solution. many thanks!
harald