How to handle a warning as an error in a Makefile?

  • Is it possible to treat warnings as errors in the Makfile (and thus exit before the Makefile continues)

  • Also, is it possible to filter out which warning gives an error?

My use case: I want to use --warn-undefined-variablesin combination with this so that the Makefile exits when the variable is undefined, which is a very common source of errors. Obviously, I do not want to manually check each variable as it is error prone / tedious. I could not find anything on this, but this is a pretty important / main function.

Note. I am not looking for -Werrorwhich is a special gcc command not applicable to my use case.

+5
source share
2 answers

The standard version of make does not support what you are looking for. However, it’s easy to create your own version of make to fulfill your use case.

After looking at the source code of make 3.82, check the macro warn_undefinedin the .h variable:

214 /* Warn that NAME is an undefined variable.  */
215 
216 #define warn_undefined(n,l) do{\
217                               if (warn_undefined_variables_flag) \
218                                 error (reading_file, \
219                                        _("warning: undefined variable `%.*s'"), \
220                                 (int)(l), (n)); \
221                               }while(0)

I have not tried this, but I think that this is enough to replace errorwith fatal.

+2
source

If you are ready to add a dependency for each goal, you can make warnings in the form of errors.

Here is the make file with an error in it ("SRCS" instead of "SRC"):

# Turn on the warning we want
MAKEFLAGS += --warn-undefined-variables

# Make sure MAKECMDGOALS is defined, so it doesn't cause an error itself
ifndef MAKECMDGOALS
MAKECMDGOALS = all
endif

SRC=hello.c

all: compile

# Fails if the Makefile contains any warnings.
# Run this Makefile with the same goals, but with the -n flag.
# Grep for warnings, and fail if any are found.
no-make-warnings:
    ! make -n $(MAKECMDGOALS) 2>&1 >/dev/null | grep warning

# Targets you want to check must depend on no-make-warnings
compile: no-make-warnings
    gcc -o hello $(SRCS)

When I started it, I see the following:

$ make
! make -n all 2>&1 >/dev/null | grep warning
Makefile:17: warning: undefined variable `SRCS'
make: *** [no-make-warnings] Error 1

You just need each goal that you want to test depends on the goal no-make-warnings.

If someone knows how to do this automatically, log in.

+3

All Articles