Search code examples
makefilesyntaxgnu-makesanitization

How to sanitize variables passed down from a top Makefile?


I am looking for guidance here as I recently encountered an issue when it came to comparisons using ifeq on variables that originated from a top-level Makefile I have no control over, and it made me wonder if there is a way to sanitize or standardize variables so that I can consistently use the same type of comparison going forward.

This is the problem I ran into, notice the use of " around values.

my_target:
ifeq ($(strip $(TOP_VAR_1)), "VALUE")
    #this comparison yields true
endif

ifeq ($(strip $(TOP_VAR_2)), VALUE)
    #this comparison yields true
endif

I was able to get these comparisons to work by trial and error based on GNU's conditional syntax guide, but this took me a great amount of time to do so.

Previous attempts include playing around with strip and quotation marks on variables and values, yet those still yielded a false equality.

e.g.

my_target:
ifeq ($(strip $(TOP_VAR_1)), VALUE)
    #this comparison yields false
endif

ifeq ($(strip $(TOP_VAR_2)), "VALUE")
    #this comparison yields false
endif

Solution

  • It's very unclear what exactly your question is. And, since you didn't show us what the actual values of the TOP_VAR_1 or TOP_VAR_2 variables are, we can't really provide any guidance.

    I will say two things: first if you use the ifeq (...) form, then GNU make completely ignores quotes (or rather, treats them as any other character and not special in any way). And second, the only thing the strip function does is remove extra whitespace. It doesn't do anything with quotes.

    So in your examples:

    ifeq ($(strip $(TOP_VAR_1)), "VALUE")
    

    This will be true if the value of the TOP_VAR_1 variable is the string "VALUE" (including the quotes!!), possibly with leading or trailing whitespace (as in, it would match "VALUE" but it would NOT match " VALUE " or VALUE etc.)

    ifeq ($(strip $(TOP_VAR_2)), VALUE)
    

    This matches if TOP_VAR_2 is the string VALUE (without quotes!) possibly with leading or trailing whitespace (as in, it would match VALUE but it would NOT match "VALUE" etc.)

    If you want to see what these variables contain the simplest way is using the info function:

    $(info TOP_VAR_2='$(TOP_VAR_2)')
    

    Whatever is inside the '' in the output is the string that ifeq will operate on. You can of course also add the strip function to see how that changes things.