Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-build step in makefile

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?

like image 636
zxcat Avatar asked Oct 23 '09 09:10

zxcat


2 Answers

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.

like image 116
Amro Avatar answered Sep 20 '22 01:09

Amro


Depending on your make version, something like the following should at least avoid running dozens of times if CFLAGS and AFLAGS are evaluated dozens of times:

CHEAT_ARG := $(shell myscript)

Note the colon.

This runs exactly once. Never more than once, but also never less than once. Choose your own tradeoffs.

like image 14
ndim Avatar answered Sep 21 '22 01:09

ndim