How to define global shell functions in a Makefile?

前端 未结 7 981
醉酒成梦
醉酒成梦 2021-02-12 12:18

I want to define a shell function

#!/bin/sh

test ()
{
  do_some_complicated_tests $1 $2;
  if something; then
    build_thisway $1 $2;
  else
    build_otherway         


        
相关标签:
7条回答
  • 2021-02-12 13:10

    TL;DR:

    In your makefile:

    SHELL=bash
    BASH_FUNC_command%%=() { ... }
    export BASH_FUNC_command%%
    

    Long answer

    I've done something similar with bash in a non-make context which works here.

    I declared my shell functions in bash and then exported them with:

    export -f function-name
    

    They are then naturally available if the same shell is invoked as a sub-process, in your case, from make.

    Example:

    $ # define the function
    $ something() { echo do something here ; }
    $ export -f something
    
    $ # the Makefile
    $ cat > Makefile <<END
    SHELL=bash
    all: ; something
    END
    $
    

    Try it out

    $ make
    something
    do something here
    $
    

    How does this look in the environment?

    $ env | grep something
    BASH_FUNC_something%%=() { echo do something here
    

    So the question for you would be how to set the environment variables from within the Makefile. The pattern seems to be BASH_FUNC_function-name%%=() { function-body }

    Directly within make

    So how does this work for you? Try this makefile

    SHELL=bash
    define BASH_FUNC_something-else%%
    () {
      echo something else
    }
    endef
    export BASH_FUNC_something-else%%
    
    all: ; something-else
    

    and try it:

    $ make
    something-else
    something else
    

    It's a bit ugly in the Makefile but presents no ugliness for make -n

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