Makefile failing when using diff on different files
Asked Answered
F

2

7

Part of my makefile for my C++ project uses the diff command to compare two files that were output by the recently built code. The issue is that if the files are different, the script should not fail and should continue. There are more files that need to be compared and I need to see them all before the build script should end. For example, something like this,

diff:   *
        diff $(TEST)/T4.board $(TEST)/T4.board
        diff $(TEST)/T4.board $(TEST)/sample.board

The first line causes no issue because the files are the same. The second line compares different files, and once the differences are displayed, I see

Makefile:102: recipe for target `diff' failed
make: *** [diff] Error 1

and the script stops. How can I get it to continue?

Flamboyant answered 11/3, 2012 at 17:34 Comment(1)
diff should return 0 on success and 1 on failure. The question is how do I deal with failure? I've only been using makefiles for a week or so.Flamboyant
S
6

Make your entire recipe to return no error:

diff:   *
    diff $(TEST)/T4.board $(TEST)/T4.board     || exit 0
    diff $(TEST)/T4.board $(TEST)/sample.board || exit 0

One can use echo 'Files differ' instead of exit 0.

Sendoff answered 11/3, 2012 at 18:3 Comment(3)
Thanks, both options work. I think it's kind of dumb though that makefiles don't have an option to ignore errors. For things like diff, returning 1 isn't the end of the world, and adding exit 0s to the end of every diff can get annoying.Flamboyant
@gsingh2011: Makefiles do have the option to ignore errors. See my answer.Scornik
@gsingh2011 Oh, I forgot about it, you can just add a minus sign (-) before the command to ignore its exit code. See thiton's answer.Sendoff
S
7

As the GNU make manual states in section 5.5 "Errors", you can ignore the return status of a command by prefixing the command with -:

diff:   *
    -diff $(TEST)/T4.board $(TEST)/T4.board
    -diff $(TEST)/T4.board $(TEST)/sample.board
Scornik answered 11/3, 2012 at 18:59 Comment(1)
+1, I forgot about such native way to suppress errors in GNU Make.Sendoff
S
6

Make your entire recipe to return no error:

diff:   *
    diff $(TEST)/T4.board $(TEST)/T4.board     || exit 0
    diff $(TEST)/T4.board $(TEST)/sample.board || exit 0

One can use echo 'Files differ' instead of exit 0.

Sendoff answered 11/3, 2012 at 18:3 Comment(3)
Thanks, both options work. I think it's kind of dumb though that makefiles don't have an option to ignore errors. For things like diff, returning 1 isn't the end of the world, and adding exit 0s to the end of every diff can get annoying.Flamboyant
@gsingh2011: Makefiles do have the option to ignore errors. See my answer.Scornik
@gsingh2011 Oh, I forgot about it, you can just add a minus sign (-) before the command to ignore its exit code. See thiton's answer.Sendoff

© 2022 - 2024 — McMap. All rights reserved.