Search code examples
makefilegnu-make

Make: How to escape spaces in $(addprefix)?


Here's what I am trying to do:

EXTRA_INCLUDE_PATHS = ../dir1/path with spaces/ \
                      ../dir2/other path with spaces/
CPPFLAGS += $(addprefix -I,$(EXTRA_INCLUDE_PATHS))

I want to get “-I../dir1/path with spaces/ […]”, but I get instead: “-I../dir/path -Iwith -Ispaces/ […]”.

How do I espace spaces in addprefix? I've tried doing this trick, but it produces same result:

space  =
space +=
#produces “-Isome -Ipath”
CPPFLAGS += $(addprefix -I,some$(space)path)

Solution

  • Don't do it! As @MadScientist points out, you need to eschew all space-containing filenames in a makefile unless you want to be very sad. A space is a list separator (including in lists of targets), and there is just no way around that. Use symbolic links in your file system to avoid them! (mklink on windows, or use cygwin make which understands cygwin symbolic links).

    That said, in the current case (where you are not defining a list of targets, but merely a list of include dirs), you could use a single character to represent a space, only translating it right at the end.

    EXTRA_INCLUDE_PATHS = ../dir1/path|with|spaces/ ../dir2/other|path|with|spaces/
    CPPFLAGS += $(subst |, ,$(patsubst %,-I'%',${EXTRA_INCLUDE_PATHS}))
    

    Check the result:

    $(error [${CPPFLAGS}])
    

    gives Makefile:3: *** [-I'../dir1/path with spaces/' -I'../dir2/other path with spaces/']. Stop.. Here, $CPPFLAGS is in sh format—the spaces are quoted with ' so that the compiler sees each -I as a single parameter. make simply does not have this level of quoting.