-1

I'm maintaining a Makefile for a project, which contains many variable declarations:

DOCKER_IMAGE_VERSION := latest
DOCKER_EXPOSE_PORT := 8080
PIP := python -m pip
...

Sometimes the lines using these variables are deleted, and these declarations become obsolete.

Is there a tool that finds unused variable declarations in a Makefile?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • I am not aware of any such. You could just use `grep`. – MadScientist Oct 25 '21 at 19:01
  • I can `grep` one by one, but most modern compilers can issue a warning for me by analyzing the AST. I hoped there's something for Makefile as well. – Adam Matan Oct 25 '21 at 20:15
  • There's no AST here. A makefile is not "compiled" per se. Every recipe is a text blob, that is passed to the shell to execute, Also there's no way to know, for any given execution of make, whether some other execution (that built some other set of targets) might have used that variable. There is no mode of GNU make that will just search through all recipes looking for variables that are referenced. – MadScientist Oct 25 '21 at 21:15

1 Answers1

0

If you can change the variables to be recursively expanded, you can use the following trick:

DOCKER_IMAGE_VERSION = latest$(warning DOCKER_IMAGE_VERSION accessed)

etc, and then grep the output to see where it's accessed. Notice that this does not work for immediate expanded variables (as the warning appears at the assignment rather than at the reference). Also notice that this will only print when the variable is expanded, so for example, if it is referenced inside of a recipe for a target that is never run, it will not output a log. Also, it will not output a log if it is in an ifdef'd location in the makefile, or as part of a logical function ($(or...),$(if ...), where the parameter is short circuited.

But, while it can miss references, what this trick is good for is if you have a makefile, where you want to assume a variable is no longer used, you can do:

SOME_VAR = $(error use of deprecated variable)
HardcoreHenry
  • 5,909
  • 2
  • 19
  • 44