variable target in a makefile

wmercer picture wmercer · Jul 1, 2011 · Viewed 22.5k times · Source

I am trying to compile set of targets. However it only seems to do the first one. Below is a cut down of the my makefile that shows the error.

  OBJECTS = abc def ghi
  SOURCES = abc.c def.c ghi.c

  $(OBJECTS):     $(SOURCES)
          @echo target is $@, source is $<

In shell,

  $ touch abc.c def.c ghi.c
  $ make

When I run make I get the following output:

  target is abc, source is abc.c

So it only seems to be running the first target.

If I replace $< with $^, the output is:

  target is abc, source is abc.c def.c ghi.c

My question, is it possible to perform expansions on variables like with the (%: %) pattern?

Answer

Beta picture Beta · Jul 1, 2011

Try this:

  OBJECTS = abc def ghi

  all: $(OBJECTS)

  $(OBJECTS):%:%.c
          @echo target is $@, source is $<

The trouble was

  1. The default target (which is what Make chooses if you just type `make`) is the first target in the makefile, which was `abc`.
  2. You made all sources prerequisites of every object. That is, all three sources were prerequisites of `abc`. They were also prerequisites of `def` and of `ghi`.