Search code examples
makefilebuildparallel-processingtarget

How to build specific multiple targets parallelly using make?


There are three source files. Each source files are corresponding targets. For example, the target of a.cpp is a, b.cpp is b, and c.cpp is c.

src/a.cpp
    b.cpp
    c.cpp
build/

I can build the targets parallelly using -j option.

For example,

cd build
make -j3

target a, b, and c build parallelly.

Is there any way to specify some of targets and parallel build ?

For example

make -j2 a b

Unfortunately, it works sequentially. First, build a and then build b. I want to build only a and b parallelly.

I tried the following approach.

make a&
make b&
wait

However, the return code of the wait is the last finished waiting target. That means if make a& finished with failure and then make b& successfully finished, the return code of wait is 0. I want to stop building process if any of make are failure.

Is there any good way ?


Solution

  • Unfortunately, it works sequentially

    That is not true, as you could see from writing a small test:

    $ cat Makefile
    all: one two
    
    one two:
            @echo start $@
            @sleep 2
            @echo stop $@
    
    $ make
    start one
    stop one
    start two
    stop two
    
    $ make -j2
    start one
    start two
    stop one
    stop two
    
    $ make -j2 one two
    start one
    start two
    stop one
    stop two
    

    As you can see even when providing specific targets on the command line, they are run in parallel. If you are not seeing this behavior then there's something about your makefiles that is materially different than what you've described in your question.