[CMake] foreach: bug or feature?

Marcel Loose loose at astron.nl
Wed Apr 29 08:58:00 EDT 2009


Hi Andreas,

Seems we disagree about the intuitiveness of the API. Maybe I've done
too much C/C++ programming ;-)

I stumbled upon this problem while I was trying to parse the input
arguments to a macro(add_package _name). This macro can be used as
follows: add_package(name [version] [DEPENDS depend depend ...])
I wanted to get all the arguments after DEPENDS. Here's a simplified
version of the macro.

  macro(add_package _name)
    set(_args ${ARGN})
    list(FIND _args DEPENDS _start)
    list(LENGTH _args _stop)
    math(EXPR _start "${_start}+1")
    math(EXPR _stop "${_stop}-1")
    message(STATUS "_index = ${_start}")
    message(STATUS "_length = ${_stop}")
    foreach(idx RANGE ${_start} ${_stop})
      list(GET _args ${idx} _arg)
      message(STATUS "_args[${idx}] = ${_arg}")
    endforeach(idx RANGE ${_start} ${_stop})
  endmacro(add_package _name)

While testing boundary condition, I noted that this macro fails when
there are no arguments after DEPENDS. In that case start > stop, so I
did not expect CMake to enter the foreach loop at all. But it did, and
triggered a list index out of range error. Now, that's what I found
counter-intuitive.

Best regards,
Marcel Loose.

On Wed, 2009-04-29 at 14:14 +0200, Andreas Pakulat wrote:
> On 29.04.09 13:56:12, Marcel Loose wrote:
> > Hi all,
> > 
> > foreach(cnt RANGE 3 1)
> >   message(STATUS "${cnt}")
> > endforeach(cnt RANGE 3 1)
> > 
> > produces the output
> > -- 3
> > -- 2
> > -- 1
> > 
> > Apparently, CMake decides to count backward whenever stop > start.
> > 
> > I find this a little counter-intuitive;
> 
> I find this rather intuitive. Its still a valid range.
> 
> I'm assuming you've stumbled over this will looking for the cause of a
> problem you have? Can you explain what problem that is?
> 
> Andreas
> 



More information about the CMake mailing list