user2167013
user2167013

Reputation: 359

How to loop an Object in GNUmakefile

I am new to GNUmakefile and what I want to do is really simple. As you can see below, OBJS contains all the *.c files under MYDir . What I want to do next is to have a program called MyProgram to run on EACH .c file stored in the OBJS . But I don’t know how to pass each .c from the OBJS to “runThis”.

Thanks

DIR := MyDir
OBJS := $(wildcard $(DIR:=/*.c))

.PHONY: all

all : $(OBJS) runThis

runThis:
        MyProgram   some.c

Upvotes: 0

Views: 53

Answers (2)

PeterSW
PeterSW

Reputation: 5261

Hear's another route:

DIR := MyDir
OBJS := $(wildcard $(DIR:=/*.c))

DUMMY_TGTS := $(addsuffix ., $(OBJS))

.PHONY: all $(DUMMY_TGTS)

all : $(DUMMY_TGTS)

$(DUMMY_TGTS) : %. : %
    MyProgram $<

As usual with stackoverflow make answers you will need to switch the indent from spaces to a tab.

It uses a Static Pattern rule to call MyProgram on each of the .c files individually. The DUMMY_TGTS are setup with .PHONYensure they will still trigger the rule even if there is a file existing with that name.

Upvotes: 1

FooF
FooF

Reputation: 4482

Most simply, you could pass the $(OBJS) (which I took the liberty of renaming to CFILES) directly in the rule:

DIR := MyDir
CFILES := $(wildcard $(DIR:=/*.c))

.PHONY: all

all:
        for f in $(CFILES); do MyProg $$f; done

This is assuming Bourne style shell (like bash, dash, ash, etc) and that your file names do not contain spaces.

You could also let the GNU make do the "hard work" of looping:

DIR := MyDir
CFILES := $(wildcard $(DIR:=/*.c))

.PHONY: all

define gen-rule
  all: process-$1

  process-$1:
        MyProg $1

endef

$(eval $(foreach c,$(CFILES),$(call gen-rule,$(c))))

For each file $(c) in $(CFILES), we create a rule process-$(c) and induce all rule to depend on that rule.

Upvotes: 1

Related Questions