Christian
Christian

Reputation: 189

GNU make special target executes common target with special option

I'm using a GNU makefile to build two variants of an application, which only differ in a macro set by -D:

var_a:
  @g++ -o binary -DVARA main.cpp

var_b:
  @g++ -o binary -DVARB main.cpp

Is there any built-in way to do this using prerquisites? My only idea is to solve this with recursive make, but I don't feel comfortable with it:

var_a:
  make binary VARIANT=VARA

binary:
  @g++ -o $@ -D$(VARIANT) main.cpp

Upvotes: 0

Views: 57

Answers (2)

Altaf
Altaf

Reputation: 3086

A cleaner approach would be to use a VARIANT handler variable and update the defs based on the VARIANT recieved.

DEFAULT_VARIANT=var_a
# -------- set default variant if none given ------ <<<
ifndef VARIANT
   VARIANT=$(DEFAULT_VARIANT)
endif

ifeq ($(VARIANT),var_a)
   DEFS = -DVARA
endif

ifeq ($(VARIANT),var_b)
   DEFS = -DVARB
endif

# Your target and recipe remains same and no recursive calls needed
binary:
  @g++ -o $@ $(DEFS) main.cpp

Execute target : make binary VARIANT=var_b

Upvotes: 0

MadScientist
MadScientist

Reputation: 101081

It is virtually never a good idea for a recipe to build a target different than $@.

You can use target-specific variables:

var_a var_b: main.cpp
        g++ -o $@ $(CPPFLAGS) $<

var_a: CPPFLAGS += -DVARA
var_b: CPPFLAGS += -DVARB

Upvotes: 1

Related Questions