Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override target in makefile to add more commands?

Tags:

makefile

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?

like image 872
Paul D. Avatar asked Oct 29 '09 16:10

Paul D.


People also ask

How do I override a makefile target?

In the containing makefile (the one that wants to include the other), you can use a match-anything pattern rule to say that to remake any target that cannot be made from the information in the containing makefile, make should look in another makefile. See Pattern Rules, for more information on pattern rules.

How do I extend a makefile?

Well on a Linux machine it usually doesn't have an extension at all - it's just "makefile" or "Makefile". You can call it anything you want and use the -f option to tell "make" which to use. If your text editor can't save a file called Makefile , use a better text editor.

What does override command do?

The Override with Save File command overrides (replaces) the file named in the program, overrides certain attributes of a file that is used by the program, or overrides the file and certain attributes of the file to be processed.


1 Answers

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.

like image 91
Eric Melski Avatar answered Sep 21 '22 15:09

Eric Melski