Search code examples
c++visual-studiomakefilenmake

How to combine macros in NMake?


I am trying to combine macro in NMake? I start like this.

nmake -f C:\Users\Administrator\Desktop\build.makefile TEST

But the output is

fatal error U1001: syntax error : illegal character '$' in macro Stop.

Instead of -03

FLAGS_PLATFORM     = %PLATFORM%
FLAGS_BUILD_TYPE   = %BUILD_TYPE%

FLAGS_X86_RELEASE  = -O3
FLAGS_X86_DEBUG    = -O3

FLAGS_X64_RELEASE  = -O3
FLAGS_X64_DEBUG    = -O3

FLAGS_COMPILER_X86 = compiler.exe
FLAGS_COMPILER_X64 = compiler.exe

FLAGS  = $(FLAGS_$(FLAGS_PLATFORM)_$(FLAGS_BUILD_TYPE))

TEST:
     echo "$(FLAGS)"

Solution

  • With GNU make (3.81, running on Mac OS X 10.10.5 Yosemite), this makefile (example.mk) works:

    FLAGS_PLATFORM     = X86
    FLAGS_BUILD_TYPE   = DEBUG
    
    FLAGS_X86_RELEASE  = -m32 -O3
    FLAGS_X86_DEBUG    = -m32 -g
    
    FLAGS_X64_RELEASE  = -m64 -O3
    FLAGS_X64_DEBUG    = -m64 -g
    
    FLAGS = $(FLAGS_$(FLAGS_PLATFORM)_$(FLAGS_BUILD_TYPE))
    
    test:
            @echo "$(FLAGS)"
    

    For example:

    $ make -f example.mk
    -m32 -g
    $ make -f example.mk FLAGS_PLATFORM=X64 FLAGS_BUILD_TYPE=RELEASE
    -m64 -O3
    $ make -f example.mk FLAGS_PLATFORM=X64 
    -m64 -g
    $ make -f example.mk FLAGS_BUILD_TYPE=RELEASE
    -m32 -O3
    $ make -f example.mk FLAGS_PLATFORM=X86 FLAGS_BUILD_TYPE=DEBUG
    -m32 -g
    $
    

    You can mix'n'match defaults built into the makefile with command-line overrides. If you chose to use environment variables, on Unix you'd use $(PLATFORM) rather than %PLATFORM% (and $(BUILD_TYPE) rather than %BUILD_TYPE%) in the makefile; make imports all the environment variables (except SHELL) and makes them available as macros.

    Note that the makefile has no trailing comments after the FLAGS_PLATFORM and FLAGS_BUILD_TYPE macros; those broke the efforts to build a variable name (unless you use the command-line overrides).

    Whether this works with GNU make on Windows, or with NMake (on Windows) is beyond my ken.