How can I write a makefile to auto-detect and parallelize the build with GNU Make?

前端 未结 7 1567
悲&欢浪女
悲&欢浪女 2021-02-01 03:37

Not sure if this is possible in one Makefile alone, but I was hoping to write a Makefile in a way such that trying to build any target in the file auto-magically detects the num

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-01 04:05

    The detection part is going to be OS dependent. Here's a fragment that will work on Linux and Mac OS X:

    NPROCS:=1
    OS:=$(shell uname -s)
    
    ifeq($(OS),Linux)
      NPROCS:=$(shell grep -c ^processor /proc/cpuinfo)
    endif
    ifeq($(OS),Darwin) # Assume Mac OS X
      NPROCS:=$(shell system_profiler | awk '/Number Of CPUs/{print $4}{next;}')
    endif
    

    To get it working you are probably going to have to re-invoke make. Then your problem is preventing infinite recursion. You could manage that by having two makefiles (the first only resetting the -j value), but it is probably possible to finesse it.

提交回复
热议问题