makefileconditional-statementsgnu-makebsdmake

How to conditionally assign value to a variable in a Makefile (BSD + GNU)?


I have a (from my point of view) rather complicated Makefile.

That is mostly because I wanted colors there and other unnecessary things.

Anyway, might I jump right into my question:

Apart from Linux I newly support *BSD, thus I need to check for the platform in use on several places. Is conditional variable assignment possible in a Makefile? Something like:


platform := [ $$(uname) = Linux ] && echo Linux || echo BSD or other

Of course this does not work, but hopefully, you get my point.


I need a solution, that works both with the BSD make, and the GNU make.


Solution

  • The != shell assignment operator is apparently supported on both BSD and GNU make:

    platform_id != uname -s
    
    platform != if [ $(platform_id) = Linux ] || \
        [ $(platform_id) = FreeBSD ] || \
        [ $(platform_id) = OpenBSD ] || \
        [ $(platform_id) = NetBSD ]; then \
            echo $(platform_id); \
        else \
            echo Unrecognized; \
        fi
    

    Note that the assignments are really evaluated by the shell: it is the result of this evaluation that gets assigned to the make variables, not the shell commands.

    Solution that requires GNU make. It works with GNU make on BSD, but not with BSD make.

    One possibility is to use the if GNU make function:

    platform := $(if $(patsubst Linux,,$(shell uname -s)),BSD or other,Linux)
    

    Another one is to rely only on the shell conditionals:

    platform := $(shell [ $$(uname) = Linux ] && echo Linux || echo BSD or other)
    

    The GNU make conditionals can also be used:

    ifeq ($(shell uname -s),Linux)
        platform := Linux
    else
        platform := BSD or other
    endif