user2532296
user2532296

Reputation: 848

conditional statements, arithmetic operation and output redirection in Makefiles

I am trying to have

I have two registers reg_a and reg_b, each are 32 bit. reg_a is used to store the epoch time (unix time), so it can go upto a maximum of 2^32 -1. If an overflow occurs, the overflow should be stored in reg_b. I also want to write them in a file rom.txt . I am trying to do this in a Makefile. This is how far I got (It is more of a pseudocode, there are syntax errors). Would be happy to know if there is a better way to do this.

   # should be 2^32-1, but lets consider the below for example  
   EPOCH_MAX = 1500000000

   identifier:

      # get the epoch value 
      epoch=$(shell date +%s)

      # initialize the reg_a, reg_b, assuming that overflow has not occurred
      reg_a=$(epoch)
      reg_b=0 

      # if overflow occurs
      if [ ${epoch} -gt $(EPOCH_MAX)] ; then \
            reg_a=$(EPOCH_MAX) ;\
            reg_b=$(shell $(epoch)\-$(EPOCH_MAX) | bc) ;\
      fi ;\ 

      # here I want to print the values in a text file
      echo $$(reg_a) > rom.txt 
      echo $$(reg_b) >> rom.txt

I am novice to Makefiles. The above is just a sort of pseudocode which tells what I want to do (Mostly through reading some webpages). I will be happy if someone can help me with the above. Thanks.

Upvotes: 1

Views: 94

Answers (1)

MadScientist
MadScientist

Reputation: 100946

you've been asking a lot of questions about make. I think you might benefit from spending some time reading the GNU make manual

Pertinent to your question, each logical line in a recipe is run in a separate shell. So, you cannot set a shell variable in one logical line, then use the results in another one.

A "logical line" is all the physical lines where the previous one ends in backslash/newline.

So:

identifier:
        # get the epoch value 
        epoch=$(shell date +%s)

        # initialize the reg_a, reg_b, assuming that overflow has not occurred
        reg_a=$(epoch)
        reg_b=0 

Will run 5 separate shells, one for each line (including the comments! Every line indented with a TAB character is considered a recipe line, even ones that begin with comments).

On the other hand, this:

       if [ ${epoch} -gt $(EPOCH_MAX)] ; then \
              reg_a=$(EPOCH_MAX) ;\
              reg_b=$(shell $(epoch)\-$(EPOCH_MAX) | bc) ;\
       fi ;\ 

Runs the entire if-statement in a single shell, because the backslash/newline pairs create a single logical line.

Second, you have to keep very clear in your mind the difference between make variables and shell variables. In the above the line epoch=$(shell date +%s) is setting the shell variable epoch (which value is immediately lost again when the shell exits).

The line reg_a=$(epoch) is referencing the make variable epoch, which is not set and so is empty.

Upvotes: 1

Related Questions