How do I a conditional build through a make file?

913 views Asked by At

How can we create selective objects by passing command line options to a make file?

My project structure is as follows.

Makefile
src/
include/
test/

The main file is under test dir & other C++ test code files, like abc1.cc abc2.cc, etc. also under test.

I want to build selective abcX.cc files into abcX.o files by passing appropriate argument to the make file.

I don't want to use my make as,

$ make ABC1=1 ABC2=1,

and put that ABC variable in ifeq in the make file.

Like,

ifeq ($(ABC1), 1)
  $(TESTPATH)/abc1.o
endif

Is there a practical approach?

1

There are 1 answers

0
mandrake On

If I understand the question correctly, you want to create the same binary but use a different source for it by providing an option to make.

For this specific scenario, just use a pattern phony/pseudo-target to make the final target:

# Create a pattern target, let's give it a name such that
# the pattern is obvious, such as ABC/<num>
.PHONY: ABC/%
ABC/%: main.cc $(TESTPATH)/abc%.cc
     g++ -o modtest $< # etc...

Then pass whatever number you wish to build to make with make ABC/<num>

$ make ABC/1

If, on the other hand you wish to produce individual binaries it's the same deal, but let the phony target depend on the final binary instead. It may look like this if the pattern is the same:

# Trigger the build for modtest-<num> with the target ABC/%
.PHONY: ABC/%
ABC/%: modtest-%

If you have more advanced dependencies from the pattern to the actual target you can specify variables that maps the pattern to whatever you need by e.g. using target or pattern specific variables:

# Set target specific variables to customize what to be built
ABC/1: OBJECTS=abc1 foo bar
ABC/2: OBJECTS=abc2
ABC/%: OBJECTS=% main