GNU makefile how to and when to quote strings

2019-01-23 23:59发布

How and when do I quote a string in a make file? What is best practice?

Is the following the way to quote?

$(warning  $(shell ls -ld "$(CURDIR)" ) )

I'm familiar with Bash where you usually quote variables to allow for embedded spaces. Do you do such in a makefile?

How should I do assignment statements with a string?

vara := "$(CURDIR)"

varb := $(CURDIR)

varc := /home/me/source

vard := "/home/me/source"

What about the space after the equal?

1条回答
狗以群分
2楼-- · 2019-01-24 00:28

You should never quote anything because of make. Make doesn't understand or parse single- or double-quote characters in any way. Every quoting character you write in a makefile will be kept as a literal quote and passed along as-is to the commands that make invokes.

So, if the shell expects and can interpret a quoted string, then you should use quotes. Where the shell doesn't expect or won't correctly interpret a quoted string, you should not use quotes.

In your examples, whether the quotes are acceptable or not depends on how those variables are used. As above, make won't do anything special with quotes, which means that vard (for example) contains the literal string "/home/me/source" (including the quotes).

If you use that value in a way where the shell will handle the quotes for you, then it's fine:

all: ; echo $(vard)

will print /home/me/source (no quotes) because the shell interprets them. But if you use the variable in a make context, for example as a target or a prerequisite:

all: $(vard)
$(vard): ; echo $@

then this is not right, because the target and prerequisite are the literal strings "/home/me/source" (including the quotes).

In general it's best to not use quotes around filenames in variables, and instead add the quotes in the recipe around the make variable. Of course if the variable contains an entire shell script, not just a filename, then you should add appropriate quoting to the script.

查看更多
登录 后发表回答