Home > Software design >  makefile loop: easily comment out some items
makefile loop: easily comment out some items

Time:04-22

I have a makefile that loops over some items like this:

all:
    for i in \
        foo \
        bar \
        baz \
    ; do \
      echo $$i ;\
    done

As I'm debugging, I'm often commenting out all but one loop line, but then I need to move these lines above the for, or else I get this error:

/bin/sh: 3: Syntax error: word unexpected (expecting "do")

Question: Is there a better way to set this up that allows easily commenting out loop lines within the makefile? Note: I don't want to have to make separate targets for each loop item.

CodePudding user response:

You're using the line continuation (trailing backslashes) so your recipe is equivalent to:

for i in foo bar baz; do echo $$i ; done

and you cannot just drop a # in the middle of all this, make would ignore the line and you would break your line continuity. You must find a shell compatible way. Example if your shell is bash, and commenting an item consists in prepending a -:

all:
    @for i in \
        foo \
        -bar \
        baz \
    ; do \
      [[ "$$i" != -* ]] && echo $$i ;\
    done

Demo:

$ make
foo
baz

CodePudding user response:

There are lots of other ways to do it, it all depends on what you want. Also since we don't have your actual makefile, just a sample, it's not clear if the actual makefile gives other opportunities to make things better. I don't know of any way that is objectively completely better than just moving the line in all cases.

One idea, since you are using make, is to pre-create the content of the loop using make variables like this:

DATA =
DATA  = foo
DATA  = bar
DATA  = baz

all:
        for i in $(DATA); do \
          echo $$i ;\
        done

Now you can comment out the line(s) of DATA = ... that you don't want.

CodePudding user response:

Another possibility is to use a variable, and filter out the unwanted entries:

list=foo bar baz

all:
   @for i in $(filter_out bar,$(list)); do \
     echo $$i
  • Related