How do I perform arithmetic in a makefile?

后端 未结 8 993
终归单人心
终归单人心 2020-12-01 10:12

Is it possible to perform some operations on variables in a makefile? For instance, defining

JPI=4
JPJ=2

Is it possible to define in the sa

相关标签:
8条回答
  • 2020-12-01 11:01

    In GNU Make with Guile support (i.e. since version 4.0) it is easy to use call to Scheme language for arithmetic or other calculations. It is done without creating any subshell or child process.

    An example

    JP-I := 4
    JP-J := 2
    JP-IJ := $(guile (* $(JP-I) $(JP-J) ))
    
    $(info JP-IJ = $(JP-IJ) )
    # prints: JP-IJ = 8
    

    See also the manual for Guile Arithmetic Functions.

    Possible check for Guile:

    ifeq (,$(filter guile,$(.FEATURES)))
      $(error Your Make version $(MAKE_VERSION) is not built with support for Guile)
    endif
    
    0 讨论(0)
  • 2020-12-01 11:02

    To add a late answer to the pool: The GNUmake table toolkit features many arithmetic functions. You can add, subtract, multiply, divide, take the modulus in base 8,10 and 16. Also there are the usual binary operations and, or, xor and not. Numbers can be around 60 digits but you can adapt this, if you need more. The code is pure GNUmake syntax and therefore portable between Windows and Unix, contrary to shell scripts - in case you want to number crunch, there may be better solutions ;) of course.

    Here is an example:

    include gmtt/gmtt.mk
    
    NUMBER_A := -12392834798732429827442389
    NUMBER_B := 984398723982791273498234
    $(info $(call add,$(NUMBER_A),$(NUMBER_B)))
    $(info $(call sub,$(NUMBER_A),$(NUMBER_B)))
    $(info $(call mul,$(NUMBER_A),$(NUMBER_B)))
    $(info $(call div,$(NUMBER_A),$(NUMBER_B)))
    $(info $(call mod,$(NUMBER_A),$(NUMBER_B)))
    

    Output:

    $ make
    -11408436074749638553944155
    -13377233522715221100940623
    -12199490762401735834920873237276176262117128241026
    -12
    -580050110938934545463581
    
    0 讨论(0)
提交回复
热议问题