How do you get the list of targets in a makefile?

后端 未结 20 1434
难免孤独
难免孤独 2020-11-30 16:50

I\'ve used rake a bit (a Ruby make program), and it has an option to get a list of all the available targets, eg

> rake --tasks
rake db:charset      # ret         


        
20条回答
  •  無奈伤痛
    2020-11-30 17:42

    This is a modification to jsp's very helpful answer (https://stackoverflow.com/a/45843594/814145). I like the idea of getting not only a list of targets but also their descriptions. jsp's Makefile puts the description as the comment, which I found often will be repeated in the target's description echo command. So instead, I extract the description from the echo command for each target.

    Example Makefile:

    .PHONY: all
    all: build
            : "same as 'make build'"
    
    .PHONY: build
    build:
            @echo "Build the project"
    
    .PHONY: clean
    clean:
            @echo "Clean the project"
    
    .PHONY: help
    help:
            @echo -n "Common make targets"
            @echo ":"
            @cat Makefile | sed -n '/^\.PHONY: / h; /\(^\t@*echo\|^\t:\)/ {H; x; /PHONY/ s/.PHONY: \(.*\)\n.*"\(.*\)"/    make \1\t\2/p; d; x}'| sort -k2,2 |expand -t 20
    

    Output of make help:

    $ make help
    Common make targets:
        make all        same as 'make build'
        make build      Build the project
        make clean      Clean the project
        make help       Common make targets
    

    Notes:

    • Same as jsp's answer, only PHONY targets may be listed, which may or may not work for your case
    • In addition, it only lists those PHONY targets that have a echo or : command as the first command of the recipe. : means "do nothing". I use it here for those targets that no echo is needed, such as all target above.
    • There is an additional trick for the help target to add the ":" in the make help output.

提交回复
热议问题