user1192525
user1192525

Reputation: 677

reuse the same rules for building different targets

I'm developing a project that includes multiple static libraries. The way in which I build them is always the same. I would like to know how I can reuse these rules for all the libraries and avoid doing copy & paste for each one. Here is an example for building a 'foo' library.

# inputs
#
FOO_LIB_NAME  := libfoo.a
FOO_SRC_DIR   := $(SRC_DIR)/foo
FOO_SRC_FILES := \
        foo_file1.cc                              \
        subdir/foo_file2.cc                       \
        subdir/foo_file3.cc                       \
        ...
FOO_CFLAGS    :=

# rules
#
FOO_SRC_FILES := $(addprefix $(FOO_SRC_DIR)/,$(FOO_SRC_FILES))
FOO_OBJ_FILES := $(subst .cc,.o,$(FOO_SRC_FILES))

$(FOO_LIB_NAME): $(FOO_OBJ_FILES)
        $(AR) rc $@ $^

$(FOO_OBJ_FILES): %.o: %.cc
        $(CXX) $(COMMON_CFLAGS) $(FOO_CFLAGS) $< -o $@

Additionally, if you have any comment about the previous excerpt of code I would be glad to know about it. I'm quite new at writing Makefiles.

Thanks in advance

Upvotes: 3

Views: 624

Answers (1)

dwikle
dwikle

Reputation: 6978

You can accomplish this with templates and the eval function in Make. The GNU Make Manual has examples in the section on eval

Here is the example from the manual:

PROGRAMS    = server client

server_OBJS = server.o server_priv.o server_access.o
server_LIBS = priv protocol

client_OBJS = client.o client_api.o client_mem.o
client_LIBS = protocol

# Everything after this is generic

.PHONY: all
all: $(PROGRAMS)

define PROGRAM_template =
 $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
 ALL_OBJS   += $$($(1)_OBJS)
endef

$(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))

$(PROGRAMS):
        $(LINK.o) $^ $(LDLIBS) -o $@

clean:
        rm -f $(ALL_OBJS) $(PROGRAMS)

Upvotes: 3

Related Questions