Run a command in GNU and BSD Makefile and store the result into a variable

gnu-make, makefile

Solution

In GNU make 4.0, the BSD operator `!=` has been added for compatibility. For versions of GNU make prior to that, you're out of luck. You'll have to use the "poor man's" method, which is a recursive make invocation.

Be very careful because the BSD operator and the GNU make `$(shell ...)` function have slightly different semantics. In your specific situation you'll not notice any difference because the output from the shell command doesn't contain any variable references (no `$`).

Problem

I would like to execute a command in a Makefile, store the result to a variable and reuse the result later. In BSD Makefile, I can use the != operator: ``` PASSWORD != openssl rand -base64 48 ``` In GNU Makefile, I can use the shell function: ``` PASSWORD := $(shell openssl rand -base64 48) ``` Is there a way to write this in such a way this is compatible with the two make? Expected output In both case, result of the command is assigned to PASSWORD, so I can reuse the same PASSWORD value in the Makefile: ``` quux: @echo $(PASSWORD) @echo $(PASSWORD) ``` If I run `make quux`, this will output twice the same password. For example: ``` $ gmake quux Y0ZrQQqLF9JK98x9UiIwWwcCN2Cq1wNqzph3ShG1RK0NeqbxWn6p4XB5zgHvfnbY Y0ZrQQqLF9JK98x9UiIwWwcCN2Cq1wNqzph3ShG1RK0NeqbxWn6p4XB5zgHvfnbY ``` This is different than to use the backtick operator. In such cases, compatible with the two make, it will run the command each time.

Original source