makefilegnu-make

Using word function in makefile with variable


I'd like to make a custom function that get the $3 as indx from series $1 and keyword $2. So I checked below one works well.

define get_indx
         @echo $(words $1)
         for n in $(shell seq 1 $(words $1)) ;\
         do \
                 echo $$n ;\
        done
endef

NLIST:= AA BB CC
$(call get_indx,$(NLIST),BB,indx)

But below does not work. It says '*** non-numeric first argument to `word' function: '$n'. Stop.'

define get_indx
       @echo $(words $1)
       for n in $(shell seq 1 $(words $1)) ;\
       do \
               echo $$n ;\
               echo $(word $$n, $1) ;\          
       done
NLIST:= AA BB CC
$(call get_indx,$(NLIST),BB,indx)

How can I access n or how can I convert to numeric?


Solution

  • If you would like to create a custom function to get index from the list, I don't think you will be able to get it out as a parameter as all parameters to a function are in only. You can make your function output a text, which you can then assign to a variable, like so:

    $ cat Makefile
    NLIST := AA BB CC
    
    # $1 - list to check
    # $2 - element to find
    # returns - index of element
    define get_index
    $(sort $(eval index_count :=) \
    $(foreach word,$(1), \
      $(eval index_count := $(index_count) x) \
      $(if $(findstring $(word),$(2)),$(words $(index_count)))) \
    )
    endef
    
    bb_index := $(call get_index,$(NLIST),BB)
    $(info >$(bb_index)<)
    $(info >$(call get_index,$(NLIST),CC)<)
    $(info >$(call get_index,$(NLIST),AA)<)
    

    The idea here is that we use a list as a counter. For every word from original list we increment the counter by adding another value to the counter list. The actual value is not important as the only thing that matters is the number of elements in the counter list. If we hit an interesting value, we output number of elements in the counter list, which represents the index at which the element was found. This output can then be stored in a variable as usual. The $(sort) function is only for getting rid of extra spaces.

    This approach might need to be made more complex if needed depending on the circumstances (whether values may repeat etc.).

    Output:

    $ make
    >2<
    >3<
    >1<