Using bash variables in Makefile

前端 未结 3 1224
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 16:58

I want to use the bash timing variables in my makefile for example in my terminal I can do this and it works

 MY_TIME=$SECONDS 
 echo $MY_TIME
相关标签:
3条回答
  • 2020-12-11 17:29
    PROGRAM_NAME = myLittleProgram
    
    ...
    
    $(PROGRAM_NAME) : myLittleProgram.o
    

    I know the above works, as it is in my own makefile (program names and object names changed to protect the innocent).


    "Variable references can be used in any context: targets, dependencies, commands, most directives, and new variable values. Here is an example of a common case, where a variable holds the names of all the object files in a program:"

    objects = program.o foo.o utils.o
    program : $(objects)
        cc -o program $(objects)
    
    $(objects) : defs.h
    

    http://web.mit.edu/gnu/doc/html/make_6.html

    0 讨论(0)
  • 2020-12-11 17:43

    By default make uses /bin/sh as the shell which executes recipe lines.

    Presumably /bin/sh doesn't support the SECONDS variable.

    You can tell make to use a different shell by assigning a value to the SHELL variable (i.e. SHELL := /bin/bash).

    Doing that will make SECONDS available but will still not allow you to carry a variable value between recipe lines as each recipe line is run in its own shell.

    So to do what you want you would need to write both of those lines on one line or continue the line over the newline.

    .PHONY: myProg
    myProg:
          MY_TIME=$SECONDS; echo $MY_TIME
    

    or

    .PHONY: myProg
    myProg:
          MY_TIME=$SECONDS; \
          echo $MY_TIME
    

    That being said you would almost certainly be better off not doing this and instead using something like date invoked at the start/end of the recipe or time invoked on the command to be timed directly instead.

    .PHONY: myProg
    myProg:
          date
          # Do something
          date
    

    or

    .PHONY: myProg
    myProg:
          time some_command
    
    0 讨论(0)
  • 2020-12-11 17:49

    the dollar sign ($MY_TIME) refers to make variables, which are not the same as bash variables.

    To access a bash variable you must escape the dollar using the double dollar notation ($$MY_TIME).

    .PHONY: myProg
    myProg:
      MY_TIME=$$SECONDS ; echo $$MY_TIME
    

    As already mentioned in Etan answer you can't split the code into multiple lines (unless you are using the backslash) since each command executes in a different subshell, making variables inaccessible to other lines.

    In the following example the value of SECONDS will be always 0, since it get reset by the spawn of the shell for the second line.

    .PHONY: myProg
    myProg:      # WRONG
      MY_TIME=$$SECONDS
      echo $$MY_TIME
    
    0 讨论(0)
提交回复
热议问题