Trailing comments after variable assignment subvert comparison

Posted by nobar on Stack Overflow See other posts from Stack Overflow or by nobar
Published on 2012-03-31T07:06:09Z Indexed on 2012/09/30 21:37 UTC
Read the original article Hit count: 230

Filed under:
|
|

In GNU make, trailing comments appended to variable assignments prevent subsequent comparison (via ifeq) from working correctly.

Here's the Makefile...

  A = a
  B = b ## trailing comment
  C = c

  RESULT :=

ifeq "$(A)" "a"
  RESULT += a
endif

ifeq "$(B)" "b"
  RESULT += b
endif

ifeq "$(C)" "c"
  RESULT += c
endif

rule:
    @echo RESULT=\"$(RESULT)\"
    @echo A=\"$(A)\"
    @echo B=\"$(B)\"
    @echo C=\"$(C)\"

Here's the output...

$ make
RESULT=" a c"
A="a"
B="b "
C="c"

As you can see from the displayed value of RESULT, the ifeq was affected by the presence of the comment in the assignment of B. Echoing the variable B, shows that the problem is not the comment, but the intervening space.

The obvious solution is to explicitly strip the whitespace prior to comparison like so...

ifeq "$(strip $(B))" "b"
  RESULT += b
endif

However this seems error prone. Since the strip operation is not needed unless/until a comment is used, you can leave out the strip and everything will initially work just fine -- so chances are you won't always remember to add the strip. Later, if someone adds a comment when setting the variable, the Makefile no longer works as expected.

Note: There is a closely related issue, as demonstrated in this question, that trailing whitespace can break string compares even if there is no comment.

Question: Is there a more fool-proof way to deal with this issue?

© Stack Overflow or respective owner

Related posts about comments

Related posts about make