Create directories using make file

前端 未结 9 2072
情深已故
情深已故 2020-11-28 21:27

I\'m a very new to makefiles and i want to create directories using makefile. My project directory is like this

+--Project  
   +--output  
   +--source  
           


        
9条回答
  •  伪装坚强ぢ
    2020-11-28 22:16

    make in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:

    outDir/someTarget: Makefile outDir
        touch outDir/someTarget
    
    outDir:
        mkdir -p outDir
    

    The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:

    $ make
    mkdir -p outDir
    touch outDir/someTarget
    $ make
    touch outDir/someTarget
    $ make
    touch outDir/someTarget
    $ make
    touch outDir/someTarget
    

    This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.

    However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:

    # The pipe symbol tells make that the following prerequisites are order-only
    #                           |
    #                           v
    outDir/someTarget: Makefile | outDir
        touch outDir/someTarget
    
    outDir:
        mkdir -p outDir
    

    This correctly yields:

    $ make
    mkdir -p outDir
    touch outDir/someTarget
    $ make
    make: 'outDir/someTarget' is up to date.
    

    TL;DR:

    Write a rule to create the directory:

    $(OUT_DIR):
        mkdir -p $(OUT_DIR)
    

    And have the targets for the stuff inside depend on the directory order-only:

    $(OUT_DIR)/someTarget: ... | $(OUT_DIR)
    

提交回复
热议问题