views:

8480

answers:

9

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 mainly use mingw/msys but would like something that works across other shells/systems too.

I tried this but it didn't work, any ideas?

ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif
+3  A: 

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
andrewdotnich
This has the advantage of working on Windows, too. Don't forget the '-' in front of the command so make doesn't bail.
Michael Burr
+10  A: 

just use this:

mkdir -p $(OBJDIR)
+1  A: 

Inside your makefile:

target:
    if test -d dir; then echo "hello world!"; else mkdir dir; fi
Lee
+2  A: 

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

Alternatively, you can use the test command:

test -d $(OBJDIR) || mkdir $(OBJDIR)
skymt
+2  A: 

Note that the -p option to mkdir is often not available on non-GNU systems.

JesperE
+2  A: 
ifeq "$(wildcard $(MY_DIRNAME) )" ""
  -mkdir $(MY_DIRNAME)
endif
Michael McCarty
A: 
$(OBJDIR):
    mkdir $@

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

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

$(OBJDIRS):
    mkdir $@

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

Martin Fido
+1  A: 

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

wmad
+1  A: 

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 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.

/Lars Hamren

Lars Hamrén
Ah, thanks, I was trying to get something like this to work. I don't want "test -d foo || mkdir foo" on several goals, since then using "make -j2" will test them at the same time, both tests giving false, and then two processes will try to mkdir, the last of them failing.
unhammer