mbadd
mbadd

Reputation: 967

Obtaining Target-Specific Variables in included Makefiles

I have two targets in my project, let's call them client.c and server.c.

If I'm building for client, I'd like to set a variable, APPS, to be:

APPS += client_app

If I'm building for server, I'd like set this variable to be:

APPS += server_app

This APPS variable is used in an included Makefile (Makefile.include), which checks to see if APPS is defined, and then parses it if it's set.

ifdef APPS
  blah blah blah
endif

I am currently trying to do this like so...

all: client server
client: APPS += client_app
client: client.$(TARGET)
  @echo $(APPS)
server: APPS += server_app
server: server.$(TARGET)
  @echo $(APPS)
include ../Makefile.include

... This builds the targets and echos out APPS when building either the client or server. However Makefile.include never sees APPS as being set.I'm assuming this is a quirk of having a Target Specific Variable.

How would I go about ensuring that my included Makefile can also see this variable?

Upvotes: 2

Views: 1125

Answers (2)

2501
2501

Reputation: 25753

The inclusion of the additional makefile is not the issue here. The variable would not be seen regardless.

The ifdef will not see the definition of the variable APPS because it is only visible to the specific target it was defined with.

Instead remove the assignments to APPS altogether and use the special variable MAKECMDGOALS, which holds the list of goals specified in the command line:

ifeq ($(MAKECMDGOALS),client)

$(info client)  #do client stuff here

else ifeq ($(MAKECMDGOALS),server)

$(info server)  #and server stuff here

else

$(error Invalid targets)

endif

Upvotes: 1

MadScientist
MadScientist

Reputation: 101111

You can't do this. Target-specific variables are only set in the context of the recipe for the target. So, they have no value when the included makefile is parsed; that's not in the context of any particular rule.

Without knowing what the blah blah blah actually does in your makefile it's difficult to suggest alternatives. However, assuming you can't simplify this and it must be a set of make directives inside an ifdef, then you can use recursive make to do this:

all: client server

client: APPS += client_app
server: APPS += server_app

client server:
        $(MAKE) APPS=$(APPS) $@.$(TARGET)

include ../Makefile.include

Upvotes: 2

Related Questions