bash 使用 GNU make 检查目录是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12239036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for existence of a directory with GNU make
提问by smilingbuddha
I am dumping all the object files of my compilation into a separate directory called
objfiles
我将我编译的所有目标文件转储到一个名为的单独目录中
objfiles
While compiling I want to check for the existence of the directory objfiles and if it does not exist (indicating re-compilation of the whole project) I want to create it.
在编译时,我想检查目录 objfiles 是否存在,如果它不存在(表示重新编译整个项目),我想创建它。
Here is my Makefile and an attempt at the problem
这是我的 Makefile 和对问题的尝试
SHELL := /bin/zsh
#All object files are dumped into OBJDIR
OBJDIR=objfiles
OBJECTS=$(OBJDIR)/main.o \
$(OBJDIR)/printdata.o \
#...
#...
COMPILER=nvcc -arch=sm_20
exec: objdir_exist $(OBJECTS)
$(COMPILER) $(OBJECTS) -o exec
@printf "\nExecutable updated!\n\n"
$(OBJDIR)/main.o: main.cu octree.h
$(COMPILER) -c $< -o $@
$(OBJDIR)/printdata.o: printdata.cu
$(COMPILER) -c $< -o $@
...
#Clean-up executables and object files
.PHONY=clean objdir_exist
clean:
rm exec
rm -r $(OBJDIR)
# Check for the existence of object files.
# If it does not exist, then create another object_file directory to dump data to.
# If it exists do nothing
objdir_exist:
if [ ! -d "$(OBJDIR)" ] then mkdir $(OBJDIR) fi
I get the following error.
我收到以下错误。
if [ ! -d "objfiles" ] then mkdir objfiles fi
zsh:[:1: ']' expected
nvcc -arch=sm_20 -c main.cu -o objfiles/main.o
Assembler messages:
Fatal error: can't create objfiles/main.o: No such file or directory
make: *** [objfiles/main.o] Error 1
Where am I going wrong?
我哪里错了?
回答by Slava Semushin
The problem is because when you write ifin one line you should use ;as line-delimiter.
问题是因为当你写if一行时,你应该使用;作为行分隔符。
So, replace
所以,更换
if [ ! -d "$(OBJDIR)" ] then mkdir $(OBJDIR) fi
by
经过
if [ ! -d "$(OBJDIR)" ]; then mkdir $(OBJDIR); fi
回答by stark
Simpler is:
更简单的是:
mkdir -p $(OBJDIR)
回答by mondaugen
The solution I found goes something like this
我找到的解决方案是这样的
BIN=exec
OBJSDIR=objs
all: $(OBJSDIR) $(BIN)
$(OBJSDIR):
if [ ! -d $(OBJSDIR) ]; then mkdir $(OBJSDIR); fi
$(OBJSDIR)/obj1.o: obj1.c header1.h
# $< expands only to first prerequisite
$(COMPILER) -c $< -o $@
$(OBJSDIR)/obj2.o: obj2.c header2.h
$(COMPILER) -c $< -o $@
$(BIN): $(OBJSDIR)/obj1.o $(OBJSDIR)/obj2.o
# $^ expands to all prerequisites
$(COMPILER) $^ -o $@
all depends on both $(OBJSDIR) and $(BIN). If $(OBJSDIR) doesn't exist, it creates it. Then it goes on to check $(BIN) and builds that if it doesn't exist or its prerequisites have changed.
一切都取决于 $(OBJSDIR) 和 $(BIN)。如果 $(OBJSDIR) 不存在,它会创建它。然后它继续检查 $(BIN) 并构建它,如果它不存在或其先决条件已更改。

