Pre-build step in makefile

zxcat picture zxcat · Oct 23, 2009 · Viewed 49.1k times · Source

How can I run a script, which must execute before all other makefile commands? And it will be nice (but not mandatory) to the script is not executed if there is nothing to build.

I've searched SO and Google, but can't find anything.

I have this workaround:

# myscript.bat output is empty
CHEAT_ARGUMENT = (shell myscript.bat)
CFLAGS += -DCHEAT_ARGUMENT=$(CHEAT_ARGUMENT)
AFLAGS += -DCHEAT_ARGUMENT=$(CHEAT_ARGUMENT)

But it's very ugly. Is there other way to run "pre-build step" in makefile?

Answer

Amro picture Amro · Oct 25, 2009

I propose two solutions. The first mimics what NetBeans IDE generates:

CC=gcc

.PHONY: all clean

all: post-build

pre-build:
    @echo PRE

post-build: main-build
    @echo POST

main-build: pre-build
    @$(MAKE) --no-print-directory target

target: $(OBJS)
    $(CC) -o $@ $(OBJS)

clean:
    rm -f $(OBJS) target

The second one is inpired by what Eclipse IDE generates:

CC=gcc

.PHONY: all clean
.SECONDARY: main-build

all: pre-build main-build

pre-build:
    @echo PRE

post-build:
    @echo POST

main-build: target

target: $(OBJS)
    $(CC) -o $@ $(OBJS)
    @$(MAKE) --no-print-directory post-build

clean:
    rm -f $(OBJS) target

Note that in the first one, pre and post builds are always called regardless of whether the main build is determined to be up to date or not.

In the second one, the post-build step is not executed if the state of the main build is up to date. While the pre-build step is always executed in both.