Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parameterize makefile targets

Tags:

makefile

I got a Makefile that does build a 32 and a 64 bit version of a project:

#############################
# 32 bit variant of test tool
#############################
hidtest_32: $(OBJS_32)
    $(CXX_32) -m32 -g $^ $(LIBS) -o hidtest_32

hid_32.o: hid.c
    $(CC_32) -m32 $(CFLAGS) $< -o hid_32.o

../hidtest/hidtest_32.o: ../hidtest/hidtest.cpp
    $(CC_32) -m32 $(CFLAGS) $< -o ../hidtest/hidtest_32.o


#############################
# 64 bit variant of test tool
#############################
hidtest_64: $(OBJS_64)
    $(CXX_64) -m64 -g $^ $(LIBS) -o hidtest_64

hid_64.o: hid.c
    $(CC_64) -m64 $(CFLAGS) $< -o hid_64.o

../hidtest/hidtest_64.o: ../hidtest/hidtest.cpp
    $(CC_64) -m64 $(CFLAGS) $< -o ../hidtest/hidtest_64.o

As you can see both variants use the exact same build procedure, except that the number 32 has been replaced with 64.

I've tried something like

hidtest64: ARCH=64
hidtest64: hidtest_64
hidtest32: ARCH=32
hidtest32: hidtest_32

hidtest_%: $(OBJS_$(ARCH))
   $(CXX_$(ARCH)) -m$(ARCH) -g $^ $(LIBS) -o $@

which does not work as expected. I guess I would need to access the part of the target that matched %, which I wasn't able to do.

Is there a way to consolidate the two variants into a single (parameterized) one?

like image 672
gorootde Avatar asked Oct 31 '22 15:10

gorootde


1 Answers

If you are using GNU Make You can write a function (a callable macro). Single $ is substituted during $(call ...) double $ is substituted when doing $(eval $(call ...)). Background information here.

define add_target
  $(info compiling hidtest_$(1)) # logged when doing $(call ...)
  $$(info evaluating hidtest_$(1)) # logged when doing $(eval $(call ...))

  hidtest_$(1): $(OBJS_$(1))
    $(CXX_$(1)) -m$(1) -g $$^ $(LIBS_$(1)) -o $$@
endef

$(eval $(call add_target,32))
$(eval $(call add_target,64))
like image 145
bobah Avatar answered Jan 04 '23 13:01

bobah