Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile: Same Rule for multiple Targets

Tags:

makefile

I've some targets (lets say 3). So after the makefile has run, I want to have 3 executable files.

Here's what I've done by now:

CC      = gcc
CFLAGS  = -Wall -pedantic -ansi

ECHO  = server_echo
ECHO_O = echo.o

FOO = server_foo
FOO_O = foo.o

ALL = $(ECHO) $(FOO)
ALL_O = ECHO_O FOO_O

all: $(ALL) 

$(ECHO): $(ECHO_O)
        $(CC) $(CFLAGS) -o $(ECHO) $(ECHO_O)

$(FOO): $(FOO_O)
        $(CC) $(CFLAGS) -o $(FOO) $(FOO_O)

.PHONY: clean
clean:         
        - rm -f $(ALL)
        - rm -f *.o
        - rm -f core

%.o: %.c
        $(CC) $(CFLAGS) -c $<

.PHONY: mci
mci: clean $(ALL) 

There I've a duplicate of rules for the targets $(ECHO) and $(FOO). Is there any way, that I can eliminate the duplication? Something like:

for target, target_o in $(ALL), $(ALL_O)
target: target_o
    $(CC) $(CFLAGS) -o target target_o
end for

Or is there another way to solve my Problem?

Thanks for your help

like image 668
waXve Avatar asked Oct 08 '13 21:10

waXve


2 Answers

For a bit larger rules, the call function or canned recipes can be useful.

Here is an untested example with the call function:

define COMPILE =
$(CC) $(CFLAGS) -o $(2) $(1)
endef

$(ECHO): $(ECHO_O)
        $(call COMPILE,$^,$@)

$(FOO): $(FOO_O)
        $(call COMPILE,$^,$@)

Here is an untested example with a canned recipe:

define COMPILE =
$(CC) $(CFLAGS) -o $@ $^
endef

$(ECHO): $(ECHO_O)
        $(COMPILE)

$(FOO): $(FOO_O)
        $(COMPILE)

The examples contain multi-line variables as well as automatic variables.

Just in case, here is a link to the tutorial that I find useful: link.

like image 54
Pavel Shishpor Avatar answered Oct 21 '22 09:10

Pavel Shishpor


Nothing easier:

$(ECHO): $(ECHO_O)
$(FOO): $(FOO_O)

$(ECHO) $(FOO):
        $(CC) $(CFLAGS) -o $@ $^

Or you can do away with the variables ECHO_O and FOO_O entirely with a static pattern rule:

$(ECHO) $(FOO): % : %.o
        $(CC) $(CFLAGS) -o $@ $^
like image 27
Beta Avatar answered Oct 21 '22 09:10

Beta