How to manually call another target from a make target?

后端 未结 3 1485
失恋的感觉
失恋的感觉 2020-12-13 01:48

I would like to have a makefile like this:

cudaLib :
    # Create shared library with nvcc

ocelotLib :
    # Create shared library for gpuocelot

build-cuda         


        
相关标签:
3条回答
  • 2020-12-13 02:29

    As you have written it, the build target will need to do something different depending on whether you have just done an ocelot or cuda build. That's another way of saying you have to parameterise build in some way. I suggest separate build targets (much like you already have), with associated variables. Something like:

    build-cuda: cudaLib
    build-ocelot: ocelotLib
    
    build-cuda build-ocelot:
        shell commands
        which invoke ${opts-$@}
    

    On the command-line you type make build-cuda (say). Make first builds cudaLib, then it carries out the recipe for build-cuda. It expands the macros before calling the shell. $@ in this case is build-cuda, thus ${opts-$@} is first expanded to ${opts-build-cuda}. Make now goes on to expand ${opts-build-cuda}. You will have defined opts-build-cuda (and of course its sister opts-build-ocelot) elsewhere in the makefile.

    P.S. Since build-cuda et. al. are not real files, you had better tell make this (.PHONY: build-cuda).

    0 讨论(0)
  • 2020-12-13 02:29

    Most versions of make set a variable $(MAKE) that you can use for recursive invocations.

    0 讨论(0)
  • 2020-12-13 02:47

    Note: This answer focuses on the aspect of a robust recursive invocation of a different target in a given makefile.

    To complement Jack Kelly's helpful answer, here's a GNU makefile snippet that demonstrates the use of $(MAKE) to robustly invoke a different target in the same makefile (ensuring that the same make binary is called, and that the same makefile is targeted):

    # Determine this makefile's path.
    # Be sure to place this BEFORE `include` directives, if any.
    THIS_FILE := $(lastword $(MAKEFILE_LIST))
    
    target:
        @echo $@  # print target name
        @$(MAKE) -f $(THIS_FILE) other-target # invoke other target
    
    other-target:
        @echo $@ # print target name
    

    Output:

    $ make target
    
    target
    other-target
    

    Using $(lastword $(MAKEFILE_LIST)) and -f ... ensures that the $(MAKE) command uses the same makefile, even if that makefile was passed with an explicit path (-f ...) when make was originally invoked.


    Note: While GNU make does have features for recursive invocations - for instance, variable $(MAKE) specifically exists to enable them - their focus is on invoking subordinate makefiles, not on calling a different target in the same makefile.

    That said, even though the workaround above is somewhat cumbersome and obscure, it does use regular features and should be robust.

    Here is the link to the manual section covering recursive invocations ("sub-makes"):

    • Recursive Use of make
    0 讨论(0)
提交回复
热议问题