Dan
Dan

Reputation: 199

Makefile target name compared to string

In a makefile I'm trying to compare the target name with a string, and depending on this set a variable with a string or another. This example illustrates what I'm trying to do:

ifeq ($@,"Target_A")
 THE_PATH="Path_a"
 THE_TARGET=$@
else
 THE_PATH="Path_b"
 THE_TARGET=$@
endif

Target_A:
    @echo $(THE_PATH)
    @echo $(THE_TARGET)

Target_B:
    @echo $(THE_PATH)
    @echo $(THE_TARGET)

This is the output when I call make passing Target_A and when I call it passing Target_B:

$ make Target_A
Path_b
Target_A

$ make Target_B
Path_b
Target_B

The fact that I always get "Path_b" indicates the ifeq always evaluates to false, but you can see that $@ contained the right string.

Why doesn't this work?

Upvotes: 3

Views: 1889

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96012

You probably want target-specific variables:

Target_A: THE_PATH="Path_a"
Target_A:
    @echo $(THE_PATH)

Since contents of a (regular) variable are expanded each time it's used, THE_TARGET=$@ can be made global.


Target-specific variables are only accesible in a target they belong to, and its dependencies.

Normally this is enough, but if you need to have global variables, you can use the same code you have in the question, with the condition changed to this:

ifneq ($(filter Target_A,$(MAKECMDGOALS)),)

$@ (which you tried to use) only works inside of a recipe, and expands to a target name that the recipe builds.

$(MAKECMDGOALS) is a global variable that contains all targets specified (as command-line parameters) when invoking make.

This option will only work if the target you're looking for was specified as a command-line parameter.

Upvotes: 6

Related Questions