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

后端 未结 20 1503
难免孤独
难免孤独 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

    As mklement0 points out, a feature for listing all Makefile targets is missing from GNU-make, and his answer and others provides ways to do this.

    However, the original post also mentions rake, whose tasks switch does something slightly different than just listing all tasks in the rakefile. Rake will only give you a list of tasks that have associated descriptions. Tasks without descriptions will not be listed. This gives the author the ability to both provide customized help descriptions and also omit help for certain targets.

    If you want to emulate rake's behavior, where you provide descriptions for each target, there is a simple technique for doing this: embed descriptions in comments for each target you want listed.

    You can either put the description next to the target or, as I often do, next to a PHONY specification above the target, like this:

    .PHONY: target1 # Target 1 help text
    target1: deps
        [... target 1 build commands]
    
    .PHONY: target2 # Target 2 help text
    target2:
        [... target 2 build commands]
    
    ...                                                                                                         
    
    .PHONY: help # Generate list of targets with descriptions                                                                
    help:                                                                                                                    
        @grep '^.PHONY: .* #' Makefile | sed 's/\.PHONY: \(.*\) # \(.*\)/\1 \2/' | expand -t20
    

    Which will yield

    $ make help
    target1             Target 1 help text
    target2             Target 2 help text
    
    ...
    help                Generate list of targets with descriptions
    

    You can also find a short code example in this gist and here too.

    Again, this does not solve the problem of listing all the targets in a Makefile. For example, if you have a big Makefile that was maybe generated or that someone else wrote, and you want a quick way to list its targets without digging through it, this won't help.

    However, if you are writing a Makefile, and you want a way to generate help text in a consistent, self-documenting way, this technique may be useful.

提交回复
热议问题