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

前端 未结 12 1636
遇见更好的自我
遇见更好的自我 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:02

    Looking at the official make documentation, here is a good way to do it:

    OBJDIR := objdir
    OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
    
    $(OBJDIR)/%.o : %.c
        $(COMPILE.c) $(OUTPUT_OPTION) $<
    
    all: $(OBJS)
    
    $(OBJS): | $(OBJDIR)
    
    $(OBJDIR):
        mkdir -p $(OBJDIR)
    

    You should see here the usage of the | pipe operator, defining an order only prerequisite. Meaning that the $(OBJDIR) target should be existent (instead of more recent) in order to build the current target.

    Note that I used mkdir -p. The -p flag was added compared to the example of the docs. See other answers for another alternative.

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

    It works under mingw32/msys/cygwin/linux

    ifeq "$(wildcard .dep)" ""
    -include $(shell mkdir .dep) $(wildcard .dep/*)
    endif
    
    0 讨论(0)
  • 2020-12-04 07:04
    ifeq "$(wildcard $(MY_DIRNAME) )" ""
      -mkdir $(MY_DIRNAME)
    endif
    
    0 讨论(0)
  • 2020-12-04 07:04

    A little simpler than Lars' answer:

    something_needs_directory_xxx : xxx/..
    

    and generic rule:

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

    No touch-files to clean up or make .PRECIOUS :-)

    If you want to see another little generic gmake trick, or if you're interested in non-recursive make with minimal scaffolding, you might care to check out Two more cheap gmake tricks and the other make-related posts in that blog.

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

    On UNIX Just use this:

    mkdir -p $(OBJDIR)
    

    The -p option to mkdir prevents the error message if the directory exists.

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

    On Windows

    if not exist "$(OBJDIR)" mkdir $(OBJDIR)
    

    On Unix | Linux

    if [ ! -d "$(OBJDIR)" ]; then mkdir $(OBJDIR); fi
    
    0 讨论(0)
提交回复
热议问题