1

Newbie question for Makefiles... why doesn't this work?

TARGET=$@

$(TARGET): * **/*
    @echo "TARGET=$(TARGET)"

Where this does?

TARGET=my_target

$(TARGET): * **/*
    @echo "TARGET=$(TARGET)"

When started with make my_target?

Result of the former is, "no rule to make target `my_target'."

In addition to the question "why this doesn't work," is there a workaround? I'd like to be able to specify an arbitrary target from the command line. I suppose I could react to an env var, but that makes the CLI clunky, e.g., make target=my_target build or similar.

I've searched, but I'm not getting the right hits to solve this. GNU make 3.81. Thanks!

balthisar
  • 185
  • 1
  • 15

1 Answers1

3

The automatic variable $@ is defined in the context of a pattern rule; outside of any rule it has no value.

If you want Make to do the same thing to whatever target you name, you can use a match-anything rule:

%:
    @echo TARGET=$@
Beta
  • 96,650
  • 16
  • 149
  • 150
  • That seems to make sense, but if I do `GIVEN = $@` in the main body, it _does_ get assigned; I can echo it in my target. In any case, using `%:` is dropping my dependencies, and then, of course, it's capturing everything. I didn't state it in my question, but I would like to capture specific targets such as `clean`, and `%:` doesn't seem to be allowing that. – balthisar Jun 07 '18 at 23:46
  • That's because by using `=` you are creating a variable containing the literal string `$@`. Then this value is expanded when you _use_ the variable `$(GIVEN)`, in the context where you use it, not the context where the variable is assigned. See https://www.gnu.org/software/make/manual/html_node/Reading-Makefiles.html for a description of when variable values are evaluated. – MadScientist Jun 08 '18 at 18:24