Runing a makefile list of target with wait

Viewed 843

I've a make file which runs several of targets , now I want to add new target that will run after some timeout, how can I do it ?

e.g.

execbin: build start run

This is running ok, however I want to add new target called test which will run after two seconds (some timeout) , how can I do that ?

execbin: build start run test

test should execute after the run has finished and also wait 2 seconds before it start , is it possible ?

2 Answers

The lazy solution would be to add a new target called 'sleep-2', and a pattern rule do:

execbin: build start run sleep-2 test

sleep-%:
        sleep $(@:sleep-%=%)

This creates a pattern rule that takes the value after the hyphen in a sleep-<> target, and uses it as the amount of time to sleep.

I will echo @MadScientists's answer that this probably will not work if you do make -j, which really does require changing the targets to depend on each other.

Adding more prerequisites to the list relies on make's behavior that it always tries to build prerequisites in order. While that is a documented requirement of POSIX, so it will always be true, it only works well if you don't use parallelism in your builds (you don't run with -j). If you do, then make can run all of those targets at the same time.

If you want to be sure that a given target does not start until another target finishes, the correct way to do it is declare a prerequisite relationship between them, not add them to the end of a different target's prerequisite list.

So, for example, if you want the test target to not start until the run target is complete, you should declare that:

test: run
        run my tests

Now, test cannot be started until run is complete. The simplest way to introduce a sleep is just to put it into the recipe for test like this:

test: run
        sleep 2
        run my tests

If you want to be more fancy and use a separate target then you need to link the prerequisites, like this:

test: sleep-2
        run my tests
sleep-2: run
        sleep 2

Unless you have lots of these I think the simple way above is easier to understand.

Related