Makefile variable assignment error in echo

前端 未结 2 1549
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 17:14

I have make file target like this

foo: 
    i = 1
    @echo $(i)

when I run the make file like this:

$ make foo 

相关标签:
2条回答
  • 2020-12-19 17:56

    The first attempt runs the command i with the parameters = and 2. A proper assignment in the shell has no spaces on either side of the equals sign.

    Your second problem is that a recipe on two physical lines will run two unrelated shell instances. The first sets a variable to a value, then exits and loses the variable. The second, unrelated instance has no idea what the first did, and of course has no trace of the variable assignment. The fix for that is to merge the two into a single line logically (you can still split the lines over several physical lines as long as you have a semicolon between them):

    foo: 
        i=1; \
        echo "$${i}"
    

    Notice also how we need to double the dollar signs in order to prevent make from interpreting them; and the proper use of quotes around strings in the shell. (In this particular case we know the string doesn't contain any shell metacharacters; but many beginners stumble over this as well.)

    GNU Make alternatively allows you to specify .ONESHELL which forces the commands in the recipe to be evaluated all in a single shell instance;

    .ONESHELL:
    foo: 
        i=1
        echo "$${i}"
    
    0 讨论(0)
  • 2020-12-19 17:57

    In the first case you instruct the make to run a shell command: i = 1.

    If you want a variable inside Makefile you should set without leading spaces/tabs.

    I assume you use GNU's make and you want to check Recipe Syntax (or similar for other makes):

    A variable definition in a “rule context” which is indented by a tab as the first character on the line, will be considered part of a recipe, not a make variable definition, and passed to the shell.

    0 讨论(0)
提交回复
热议问题