21

This is slightly different from Can a Makefile execute code ONLY when an error has occurred?.

I'd like a rule or special target that is made whenever an error occurs (independent of the given target; without changing the rule for every target as the other answer seems to imply with the || operator).

In dmake there is special target .ERROR that is executed whenever an error condition is detected. Is there a similar thing with GNU make?

(I'm still using GNU make 3.81, but I didn't find anything in the documentation of the new GNU make 4.0 either)

Community
  • 1
  • 1
pesche
  • 3,054
  • 4
  • 34
  • 35
  • No, GNU make does not support this. You can do it if you use recursion to wrap the "main" make and then run a command if it fails, but that's about it. – MadScientist Jan 14 '14 at 16:11

1 Answers1

25

Gnu doesn't support it explicitly, but there's ways to hack almost anything. Make returns 1 if any of the makes fail. This means that you could, on the command line, rerun make with your error rule if the first make failed:

make || make error_targ

Of course, I'll assume you just want to put the added complexity within the makefile itself. If this is the case, you can create a recursive make file:

all: 
     $(MAKE) normal_targ || $(MAKE) error_targ

normal_targ:
      ... normal make rules ...

error_targ:
      ... other make rules ...

This will cause the makefile to try to build normal_targ, and iff it fails, it will run error_targ. It makes it a bit harder to read the makefile for the inexperienced, but it puts all the logic in one place.

blackghost
  • 1,730
  • 11
  • 24
  • How can I get the error code/message from `normal_targ` so that `error_targ` could display some custom error message containing a description of the error? – JHH Oct 07 '19 at 11:09
  • This is simply genius – Fayeure Feb 20 '21 at 21:17
  • @JHH Maybe you can do this by using shell `$?` variable, when make fails it returns an error code on this variable so you could do a thing like that `$(MAKE) normal_targ || echo $$? && $(MAKE) error_targ` (this would just print the error value but you can use this value to print a custom message) – Fayeure Feb 20 '21 at 21:29