i_rigia
i_rigia

Reputation: 86

How to let MAKEFILE retain the backslash sequences within a string when used in a make rule?

This is my first question on Stackoverflow so forgive me if I ask anything ridiculous :D.

Problem:
Suppose I want to compile a program that is in the directory "my dir/" with a space in it. Say the pathname of the program is "my dir/test.c".

Here is the sample makefile that I was trying out:

CC = gcc
DIR = my\ dir
$(DIR)/test.out: $(DIR)/test.c
#   $(CC) $< -o $@
    $(CC) $(DIR)/test.c -o $(DIR)/test.out



As you can see that in the last line(line-5) I have written the pathnames of the source and the output files directly as written in the prerequisite and the target, respectively. Doing this works fine because it yields the command:
gcc my\ dir/test.c -o my\ dir/test.out
which a syntactically correct way of passing filenames(with spaces) to gcc or any other shell command.

The second last line(line-4) is where the problem is(commented line). I've used automatic variables $@ (Target) and $< (First and the only Prerequisite) to produce the filename arguments for gcc which I expected to be
my\ dir/test.out and my\ dir/test.c, respectively. But here, for some reason, the produced filenames are my dir/test.out and my dir/test.c and hence the yielded command is:
gcc my dir/test.c -o my dir/test.out
Now here, gcc considers my and dir/test.c as different two different input filenames and the command generates errors.
Here is a screenshot of the generated error output when I uncomment line-4 and comment line-5 of the above Makefile:
make output

My Question:
Is there any way to retain those backslashes even by using automatic variables the way I did? Or is there any alternative that will achieve the same goal as using automatic variables and also solve my problem? Because flexibility is important here.

Thanks in advance for your help!!!

Upvotes: 2

Views: 1222

Answers (1)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21502

Use double or single quotes for the automatic variables.

Use single quotes, if you want to avoid shell expansion of the values referenced by the automatic variables:

$(DIR)/test.out: $(DIR)/test.c
    $(CC) '$<' -o '$@'

Double quotes allow shell expansion. For example, if there was a dollar sign in DIR:

DIR := $$my\ dir

then "$@" would expand to "$my dir", and the shell would interpret $my as variable.

Upvotes: 1

Related Questions