Search code examples
makefileincludeconditional-statements

Conditional inclusion of sub-Makefiles based on ifeq test


Is there a way to conditionally include a sub-Makefile based on the result of a an ifeq test as suggested below

CC = g++
CENTOS_VERSION := $(shell rpm -E %{rhel})   

TARGET = main

$(TARGET): $(TARGET).cpp
ifeq ($(CENTOS_VERSION),6)
    @echo "Building on CentOS 6"
    include(CentOS6_Makefile.mk)
else
    @echo "Building on CentOS 7"
    include(CentOS7_Makefile.mk)
endif
    $(CC) $(CFLAGS) -o $(TARGET) $(TARGET).cpp

This does not work and generates the error message

Building on CentOS 6
include(CentOS6_Makefile.mk)
/bin/sh: -c: line 0: syntax error near unexpected token `CentOS6_Makefile.mk'
/bin/sh: -c: line 0: `include(CentOS6_Makefile.mk)'
make: *** [main] Error 1

Based on the answer by @MadScientist the solution to my problem boils down to just 2 lines

CENTOS_VERSION := $(shell rpm -E %{rhel})
include CentOS$(CENTOS_VERSION)_Makefile.mk

Solution

  • Your problem is not related to ifeq; if you remove the ifeq and always include one or the other you'll see the same problem.

    First, your syntax for including files is wrong. There are no parentheses around filenames in make's include directive. It should just be:

    include CentOS6_Makefile.mk
    

    Second, you cannot use makefile processor commands like include as part of a recipe (that is, indented by a TAB). In a make recipe ALL lines that indented by TAB are passed to the shell as commands to run to build the target, they are not interpreted by make (except to expand macros). Also, you cannot include some other makefile in the middle of a recipe: once make starts to include a new makefile that's the end of any recipe that is currently being defined.

    You can do this:

    CENTOS_VERSION := $(shell rpm -E %{rhel})   
    ifneq ($(CENTOS_VERSION),6)
        CENTOS_VERSION := 7
    endif
    
    include CentOS$(CENTOS_VERSION)_Makefile.mk
    
    $(TARGET): $(TARGET).cpp
            @echo "Building on CentOS $(CENTOS_VERSION)"
            $(CC) $(CFLAGS) -o $(TARGET) $(TARGET).cpp