How to break a string across lines in a makefile without spaces?

北慕城南 提交于 2019-12-08 15:57:27

问题


In a makefile, escaping a new-line with \ allows to split a single-line long string content across multiple source lines. However, the new-line is replaced with a space. Is there a transparent line break in the source that does not affect the string content?

VAR=w\
o\
r\
d

all:
    echo $(VAR)

The desired output is 'word', but the actual output is 'w o r d'.


回答1:


The simplest solution is to use $\<newline> to split the line (at least if you are using GNU Make):

VAR = w$\
      o$\
      r$\
      d

all:
    echo $(VAR)

The output will be "word" with no spaces. This is because GNU Make will replace backslash-newline-whitespace with a single space, making the assignment to VAR be equivalent to:

VAR = w$ o$ r$ d

From https://www.gnu.org/software/make/manual/html_node/Reference.html#Reference: "A dollar sign followed by a character other than a dollar sign, open-parenthesis or open-brace treats that single character as the variable name." So the $<space> pairs are expansions of the variable whose name is a single space character. Since this variable is not defined by default, it will expand to the empty string.

Note that the variable VAR will still contain the $<space> pairs until it is expanded. Most of the time, this doesn't matter, but if your makefile depends on using $(value VAR) to process the underlying (unexpanded) value, the above technique may provide surprising results.

For other ideas, see my answer to a similar question here: How can I break a variable definition across multiple lines in a Makefile without spaces?

A longer treatment of line continuation options can be found in my article "GNU Make line continuations": http://drmikehenry.com/gnu-make-line-continuations/




回答2:


This was just asked yesterday: How can I break a variable definition across multiple lines in a Makefile without spaces?

The short answer is no, there's no way to do that. This behavior is required by the POSIX standard for make.

All you can do is try postprocessing the string to remove the whitespaces using $(subst ...) or similar.



来源:https://stackoverflow.com/questions/21246165/how-to-break-a-string-across-lines-in-a-makefile-without-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!