Search code examples
bashmakefile

How to use if and else statement in a Makefile?


Problem

I am trying to use if and else statement in a Makefile but all the things I tried down below are not working.

What I tried

The command that I putted on the terminal was:

MinGW32-make test

These variables are at the top of the Makefile:

true = 1
false = 0

ifneq statement:

test:
    ifneq ($(true), $(false))
        echo "1";
    
    else
        echo "2";
    endif

Bash if:

test:
    if [[ "a12" = "a12" ]]; then
        echo "12";
    fi

Important Details

OS : Windows
Text Editor : VScode
I am using mingw64

Solution

  • ifeq, ifneq, etc. are makefile operations, not shell operations. That means that they cannot be indented by a TAB character in a recipe, because everything indented by a TAB character in a recipe is assumed to be a shell command and is passed to the shell.

    If you write this:

    test:
    ifneq ($(true), $(false))
            echo "1"
    else
            echo "2"
    endif
    

    then it will work, although that may not be what you want to do (your example seems so simple and far-removed from what you really want to do, that likely any of our advice will not be that helpful--when coming up with examples it's best if it is as close to what you really want to do as possible, while still being simple).

    The reason your shell script examples fail is that every logical line in a recipe is sent to a different shell. So when you write:

    test:
            if [[ "a12" = "a12" ]]; then
                echo "12";
            fi
    

    make first invokes a shell with just the first line: if [[ "a12" = "a12" ]]; then. That is not a valid shell script so you get an error. If you want to send multiple physical lines into one shell script you have to use backslashes to continue them into a single logical line:

    test:
            if [[ "a12" = "a12" ]]; then \
                echo "12"; \
            fi