有没有办法在makefile或CMake文件中并行循环多个列表?
我想在CMake中执行以下操作,但AFAICT不支持此语法:
set(a_values a0 a1 a2)
set(b_values b0 b1 b2)
foreach(a in a_values b in b_values)
do_something_with(a b)
endforeach(a b)
这将执行:
do_something_with(a0 b0)
do_something_with(a1 b1)
do_something_with(a2 b2)
我会接受CMake或Make的答案,但CMake会更受欢迎。谢谢!
答案 0 :(得分:20)
你走了:
set(list1 1 2 3 4 5)
set(list2 6 7 8 9 0)
list(LENGTH list1 len1)
math(EXPR len2 "${len1} - 1")
foreach(val RANGE ${len2})
list(GET list1 ${val} val1)
list(GET list2 ${val} val2)
message(STATUS "${val1} ${val2}")
endforeach()
答案 1 :(得分:9)
从CMake 3.17开始,foreach()
循环支持ZIP_LISTS
选项,以同时遍历两个(或更多)列表:
set(a_values a0 a1 a2)
set(b_values b0 b1 b2)
foreach(a b IN ZIP_LISTS a_values b_values)
message("${a} ${b}")
endforeach()
此打印:
a0 b0
a1 b1
a2 b2
答案 2 :(得分:2)
在make
中,您可以使用GNUmake table toolkit通过将两个列表视为1列表来实现此目的:
include gmtt/gmtt.mk
# declare the lists as tables with one column
list_a := 1 a0 a1 a2 a3 a4 a5
list_b := 1 b0 b1 b2
# note: list_b is shorter and will be filled up with a default value
joined_list := $(call join-tbl,$(list_a),$(list_b), /*nil*/)
$(info $(joined_list))
# Apply a function (simply output "<tuple(,)>") on each table row, i.e. tuple
$(info $(call map-tbl,$(joined_list),<tuple($$1,$$2)>))
输出:
2 a0 b0 a1 b1 a2 b2 a3 /*nil*/ a4 /*nil*/ a5 /*nil*/
<tuple(a0,b0)><tuple(a1,b1)><tuple(a2,b2)><tuple(a3,/*nil*/)><tuple(a4,/*nil*/)><tuple(a5,/*nil*/)>