【问题标题】:trailing whitespace in Makefile variableMakefile 变量中的尾随空格
【发布时间】:2012-02-02 16:46:53
【问题描述】:

Makefile:

#there is a whitespace after "/my/path/to"
FOO = "/my/path/to"
BAR = "dir"

INCLUDE_DIRS = $(FOO)/$(BAR) "/another/path"

INCLUDES = $(foreach dir,$(INCLUDE_DIRS),-I$(dir))

all:
     @echo $(INCLUDES)

使用 Gnu make 我希望我的 $(INCLUDES) 是:

-I/my/path/to/dir -I/another/path

但是,如果行

FOO = "/my/path/to"

以空格结尾(这是一个常见的“错误”),变量 FOO 将包含空格,生成的 INCLUDES 将包含三个目录(两个第一个比第一个拆分):

-I/my/path/to -I/dir -I/another/path

我找到的唯一解决方案是使用strip函数:

FOO = $(strip "/my/path/to" )

但是没有更自然的语法,或者有什么方法可以避免这个陷阱吗?

【问题讨论】:

    标签: makefile


    【解决方案1】:

    首先,请注意路径周围可能不应该有双引号。在您的示例中,我猜$(FOO)/$(BAR) 的值将是"/my/path/to"/"dir" 而不是预期的/my/path/to/dir

    回答你的问题,一般来说,没有。连接两个值会保留空格,所以如果你想写$(FOO)/$(BAR),你需要保证$(FOO)$(BAR) 都是没有前导或尾随空格的单个单词。 strip 功能足以删除后者(如果有的话)。

    但是,您可以将这些变量之一视为一个列表并编写类似$(FOO:%=%/$(BAR)) 的内容,这样就可以正常工作。但就我个人而言,我更愿意检查FOO 的值(修复它或者如果它不好则失败并出现错误)然后照常使用它,例如:

    FOO = /my/path/to # <- a space!
    BAR = dir
    
    ...
    
    ifneq ($(word 2,[$(FOO)]),)
      $(error There is a whitespace inside the value of 'FOO')
    endif
    

    【讨论】:

      【解决方案2】:

      基于 Eldar Abusalimov 解决方案,这里有一个可以在循环中使用的函数 检查多个目录是否有空格:

      FOO = /my/path
      BAR = to # <- a space!
      BAZ = dir
      
      # $(call assert-no-whitespace,DIRECTORY)
      define assert-no-whitespace
        $(if $(word 2,[$($1)]),$(error There is a whitesapce inside variable '$(1)', please correct it),)
      endef
      
      CHECK_FOR_WHITESPACE = \
        FOO \
        BAR 
      
      $(foreach dir,$(CHECK_FOR_WHITESPACE),$(call assert-no-whitespace,$(dir)))
      
      all:
        @echo $(FOO)/$(BAR)/$(BAZ)
      

      【讨论】:

        猜你喜欢
        • 2012-10-31
        • 2021-10-22
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-25
        • 2011-04-05
        相关资源
        最近更新 更多