Home > Net >  How to maintain a shell function definition inside a Makefile?
How to maintain a shell function definition inside a Makefile?

Time:07-18

This is the script I intend to run in a Makefile:

default:
    myFunc() { echo "Called"; };
    myFunc;

When I call make, the function is not defined. So I made the following changes:

default:
    myFunc() { echo "Called"; }; myFunc;

Which allows the call to the function to work as intended.

However, I want to reuse the function definition in subsequent commands which will not be in the same line as the function definition.

Is there a way to extend the scope of a shell function definition to the whole rule?

CodePudding user response:

Note that the below is written scoped to your question where the goal is to make a function declaration apply "to the whole rule", not to the entire makefile as a whole; folks attempting to do the latter may need to ask a separate question.


Using GNU make: The .ONESHELL feature

As @MadScientist pointed out in a comment, GNU make (starting in version 3.82, released in 2010) also offers a .ONESHELL feature, which invokes a single shell with all the lines in a rule. Using this, the code might look like:

.ONESHELL:
default:
        myFunc() { echo "Called"; }
        myFunc

Portable Standard Practice: Line Continuations

By contrast, to be portable to non-GNU make implementations, one would use line continuations:

default:
        myFunc() { echo "Called"; }; \
        myFunc
  • Related