"heritage" in Makefile

301 Views Asked by At

I'm looking a way to overload parts of a Makefile A to another one B, hence extending A.

For instance we have the following makefile A:

TEXT="AHAHA"

default: after-default

before-default: 
    echo "BEFORE DEFAULT"

default: before-default
    echo ${TEXT}

after-default: default
    echo "AFTER DEFAULT"

I want to reuse it in a new Makefile B like this:

TEXT="HIHIHI"

before-default: 
    echo "NEW BEFORE DEFAULT"

The new makefile will print:

NEW BEFORE DEFAULT
HIHIHI
AFTER DEFAULT

This example is a bit absurd it is not possible like this way, but I want to know if it is possible to make such Makefile composition close to this idea.

2

There are 2 best solutions below

0
On

Your example will be trivially fulfilled by adding include A at the start of B. The new before-default target will override the old one.

vnix$ tail *
==> A <==
TEXT="AHAHA"

before-default: default
        echo "BEFORE DEFAULT"

default: after-default
        echo ${TEXT}

after-default:
        echo "AFTER DEFAULT"

==> B <==
include A

TEXT="HIHIHI"

before-default: default
        echo "NEW BEFORE DEFAULT"

vnix$ make -sf A
AFTER DEFAULT
AHAHA
BEFORE DEFAULT

vnix$ make -sf B
B:6: warning: overriding commands for target `before-default'
A:4: warning: ignoring old commands for target `before-default'
AFTER DEFAULT
HIHIHI
NEW BEFORE DEFAULT

This isn't a very good design, though; parametrizing things like you already do with TEXT comes with fewer surprises than having code that is being overridden elsewhere.

(See my comment above re: why the output is in the opposite order from what you were hoping.)

0
On

You can do this:

File Makefile:

# Define default TEXT
TEXT := HAHAHA

# Define default target
after:
    @echo AFTER

run:
    @echo $(TEXT)

before:
    @echo BEFORE

# Define dependencies
run: before
after: run

# Include the new makefile
include inheritance.mk

File inheritance.mk:

# Redefine TEXT
TEXT := HIHIHI

# Redefine before target
before:
    @ echo NEW BEFORE

When you run make you'll have some warning but it'll work as expected:

inheritance.mk:4: warning: overriding commands for target `before'
Makefile:10: warning: ignoring old commands for target `before'
NEW BEFORE
HIHIHI
AFTER