4
votes

To simplify my question, if I have a Makefile as below

    %: %.c
           gcc -o $@ $<

    make foo

Make foo will build the executable foo from foo.c. No issues. If I were to change the Makefile as below, so that I can pass the target from Makefile command-line

    # To make things little complex
    TARG=$(EXE)
    $(TARG): %.c
            gcc -o $@ $<

    make EXE=foo

The above command make EXE=foo says:

"make: *** No rule to make target %.c, needed byfoo'. Stop.`

Why is $(TARG) not getting expanded in the target rule in Makefile?

2

2 Answers

2
votes

I think you need Static Pattern rule

TARG=$(EXE)

$(TARG):%: %.c
  gcc -o $@ $<

make EXE=foo
1
votes

Just leave the code from your first example and add the following line:

.DEFAULT_GOAL := $(EXE)

Or (which is effectively the same) add $(EXE) : rule with no recipe before any other rules. By default Make picks the first target defined in the Makefile, if nothing is specified on the command line.