developer tip

mkdir을 사용할 때 makefile에“directory already already error”가 발생하지 않도록하는 방법

optionbox 2020. 8. 6. 08:15
반응형

mkdir을 사용할 때 makefile에“directory already already error”가 발생하지 않도록하는 방법


makefile에 디렉토리를 생성해야하며 "디폴트가 이미 존재합니다"라는 오류를 반복해서 무시하고 싶지만 무시하고 싶습니다.

나는 주로 mingw / msys를 사용하지만 다른 쉘 / 시스템에서도 작동하는 것을 원합니다.

나는 이것을 시도했지만 작동하지 않았다. 어떤 아이디어?

ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif

UNIX에서는 다음을 사용하십시오.

mkdir -p $(OBJDIR)

mkdir에 대한 -p 옵션은 디렉토리가 존재하는 경우 오류 메시지를 방지합니다.


공식 make documentation을 보면 좋은 방법이 있습니다.

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)

여기에서 | 파이프 오퍼레이터, 오더 만 전제 조건 정의. 현재 타겟을 빌드하려면 타겟이 최신이$(OBJDIR) 아닌 존재해야 함을 의미합니다 .

내가 사용했습니다 mkdir -p. -p플래그가 문서의 예를 비교 하였다. 다른 대안에 대한 다른 답변을 참조하십시오.


테스트 명령을 사용할 수 있습니다 :

test -d $(OBJDIR) || mkdir $(OBJDIR)

다음은 컴파일러 출력 디렉토리를 만들기 위해 GNU make와 함께 사용하는 요령입니다. 먼저이 규칙을 정의하십시오.

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

그런 다음 해당 디렉토리의 .d 파일에 따라 디렉토리로 이동하는 모든 파일을 작성하십시오.

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

$ ^ 대신 $ <를 사용하십시오.

마지막으로 .d 파일이 자동으로 제거되는 것을 방지하십시오.

 .PRECIOUS: %/.d

.d 파일을 건너 뛰고 디렉토리에 직접 의존하는 경우 파일을 해당 디렉토리에 쓸 때마다 디렉토리 수정 시간이 업데이트되므로 make를 호출 할 때마다 다시 작성해야합니다.


디렉토리가 이미 존재하는 것이 문제가 아닌 경우 해당 명령에 대해 stderr를 리디렉션하여 오류 메시지를 제거 할 수 있습니다.

-mkdir $(OBJDIR) 2>/dev/null

메이크 파일 내부 :

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

On Windows

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

On Unix | Linux

if [ ! -d "$(OBJDIR)" ]; then mkdir $(OBJDIR); fi

ifeq "$(wildcard $(MY_DIRNAME) )" ""
  -mkdir $(MY_DIRNAME)
endif

$(OBJDIR):
    mkdir $@

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

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

$(OBJDIRS):
    mkdir $@

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


It works under mingw32/msys/cygwin/linux

ifeq "$(wildcard .dep)" ""
-include $(shell mkdir .dep) $(wildcard .dep/*)
endif

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.


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.

참고URL : https://stackoverflow.com/questions/99132/how-to-prevent-directory-already-exists-error-in-a-makefile-when-using-mkdir

반응형