Benjamin Leinweber
Benjamin Leinweber

Reputation: 2944

Checking for defined variables in makefile macros

I'm having some trouble getting a GNU Makefile macro to work the way I would like it to. Here's my test:

TEST1 = defined
#TEST2 = defined

define add_ext
ifndef $(1)
    $(error $(1) not defined)
endif

$(1)_EXT = $(1).extended
endef

TESTS = TEST1 TESTS2

$(foreach test,$(TESTS),$(eval $(call add_ext,$(test))))

all:
    @echo TEST1: $(TEST1), $(TEST1_EXT)
    @echo TEST2: $(TEST2), $(TEST2_EXT)

The macro is supposed to accept the name of a variable and the macro first checks that it is already defined, then creates an associated variable.

Given that I have commented out TEST2, I was expecting this to fail on TEST2. But this is the error message:

Makefile:15: *** TEST1 not defined.  Stop.

This is very similar to what Buildroot does in their Makefiles: https://git.buildroot.net/buildroot/tree/package/pkg-generic.mk#n409

Anyone know where my trouble is?

Upvotes: 1

Views: 1204

Answers (1)

Mike Kinghan
Mike Kinghan

Reputation: 61272

You need to escape make-functions within the macro definition, i.e.

define add_ext
ifndef $(1)
$$(error $(1) not defined)
endif

$(1)_EXT = $(1).extended
endef

Also, in your:

ifndef $(1)
    $(error $(1) not defined)
endif

I can't tell whether $(error ...) is indented by tab or spaces, but it must not be tab-indented, so best not indent at all.

Upvotes: 1

Related Questions