pedrosaurio
pedrosaurio

Reputation: 4926

How the get the length of a vector in a makefile and use it in a for loop?

How can I get the dimension of a vector in a makefile? I want to have a simple loop that goes through each element of 2 same-sized vectors.

Example that doesn't work in terms of loop nor size of vectors but to give you an idea of what I am thinking about. The loop notation was taken from this:

V1=one two three four
V2=bird stones parks bears
print:
     size={#$(V1)}      <- this is my invented notation, obviously it doesn't work.
     i=0
     while [[ $$i -le $$size ]] ; do \ 
    echo $(V1)[i] $(V2)[i] ; \
    ((i = i + 1)) ; \
done

Output:

one bird
two stones
three parks
four bears

Upvotes: 3

Views: 3953

Answers (3)

jcomeau_ictx
jcomeau_ictx

Reputation: 38472

# idea from http://stackoverflow.com/a/1491012/493161
V1 ?= one two three four
V2 ?= bird stones parks bears
COUNT := $(words $(V1))
SEQUENCE := $(shell seq 1 $(COUNT))
print:
    $(foreach number, $(SEQUENCE), \
     echo $(word $(number), $(V1)) $(word $(number), $(V2));)

in action:

jcomeau@aspire:/tmp$ make -s -f answer.mk 
one bird
two stones
three parks
four bears

Upvotes: 2

user2672165
user2672165

Reputation: 3049

Another variant without loop:

V1=one two three four
V2=bird stones parks bears
print:
    @echo $(subst -, ,$(join $(V1),$(addprefix -,$(addsuffix :,$(V2))))) | sed 's/:\( \)*/\n/g'

Upvotes: 1

sgauria
sgauria

Reputation: 458

I am not sure this structure is a good fit for a Makefile. I think it would be best to put all the loop inside a perl script and just call the perl script from the Makefile. That said, here's how I would write this if I had to write it in an all make + linux way :

V=one:bird two:stones three:parks four:bears
print:
    @for vv in $(V) ; do echo $${vv} | sed 's/:/ /' ; done

which generates

one bird
two stones
three parks
four bears

Also AFAIK, a line like V1=one two three four does not create a vector. It creates the string "one two three four".

Upvotes: 2

Related Questions