how to prevent “directory already exists error” in a makefile when using mkdir

前端 未结 12 1637
遇见更好的自我
遇见更好的自我 2020-12-04 06:44

I need to generate a directory in my makefile and I would like to not get the \"directory already exists error\" over and over even though I can easily ignore it.

I

相关标签:
12条回答
  • 2020-12-04 07:07

    If having the directory already exist is not a problem for you, you could just redirect stderr for that command, getting rid of the error message:

    -mkdir $(OBJDIR) 2>/dev/null
    
    0 讨论(0)
  • 2020-12-04 07:08

    Inside your makefile:

    target:
        if test -d dir; then echo "hello world!"; else mkdir dir; fi
    
    0 讨论(0)
  • 2020-12-04 07:12

    Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:

      %/.d:
              mkdir -p $(@D)
              touch $@
    

    Then make all files that go into the directory dependent on the .d file in that directory:

     obj/%.o: %.c obj/.d
        $(CC) $(CFLAGS) -c -o $@ $<
    

    Note use of $< instead of $^.

    Finally prevent the .d files from being removed automatically:

     .PRECIOUS: %/.d
    

    Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.

    0 讨论(0)
  • 2020-12-04 07:13

    If you explicitly ignore the return code and dump the error stream then your make will ignore the error if it occurs:

    mkdir 2>/dev/null || true
    

    This should not cause a race hazard in a parallel make - but I haven't tested it to be sure.

    0 讨论(0)
  • 2020-12-04 07:17
    $(OBJDIR):
        mkdir $@
    

    Which also works for multiple directories, e.g..

    OBJDIRS := $(sort $(dir $(OBJECTS)))
    
    $(OBJDIRS):
        mkdir $@
    

    Adding $(OBJDIR) as the first target works well.

    0 讨论(0)
  • 2020-12-04 07:19

    You can use the test command:

    test -d $(OBJDIR) || mkdir $(OBJDIR)
    
    0 讨论(0)
提交回复
热议问题