齐天大圣
齐天大圣

Reputation: 1189

Makefile: read input variable and set several variables

I have a makefile where I want to read file name from input and then make other names based on it`s name. I have tried the following code

mlext = .ml
testext = test.ml
nativeext = test.native

test: 
    @read -p "Enter file name: " file; \
    echo $$file$(mlext); \
    echo $$file$(testext); \
    echo $$file$(nativeext)

for example:

If i type: foo

then I want to get foo.ml, footest.ml, footest.native

however, I can only get foo.ml. For the rest two i only get .ml and .native

How can i fix this?

Upvotes: 2

Views: 4008

Answers (1)

Virgile
Virgile

Reputation: 10148

First, let us see what is the exact recipe given to the shell by removing the @ in your Makefile:

read -p "Enter file name: " file; \
echo $file.ml; \
echo $filetest.ml; \
echo $filetest.native;

The issue is thus that the content of $(testext) gets appended to $$file, creating the shell variable $filetest, which (very probably) does not exist, resulting in an empty string in the end. This does not occur with $(mlext), as the initial dot cannot be part of a variable name.

To overcome this, use $${file} instead of $$file in your Makefile rule.

Upvotes: 3

Related Questions