make_01_Program_02_makefile 如何判断文件在不在
在 Makefile 中,判断一个文件是否存在可以通过使用 if
函数和 Make 内置的条件判断来实现。GNU Make 提供了一种方法,可以使用 test
命令或通过检查变量来确定文件的存在性。
方法 1:使用 shell
命令
可以利用 shell
函数和 test
命令来检查文件是否存在。以下是一个示例:
FILE = myfile.txt
ifeq ($(shell test -e $(FILE) && echo yes),yes)
FILE_EXISTS = true
else
FILE_EXISTS = false
endif
all:
@if [ "$(FILE_EXISTS)" = "true" ]; then \
echo "File $(FILE) exists."; \
else \
echo "File $(FILE) does not exist."; \
fi
运行示例
如果 myfile.txt
存在,输出将是:
File myfile.txt exists.
如果 myfile.txt
不存在,输出将是:
File myfile.txt does not exist.
方法 2:使用变量和 wildcard
另一种方法是利用 wildcard
函数来检查文件是否存在。wildcard
会返回匹配到的文件名,如果文件不存在,返回空字符串。
FILE = myfile.txt
EXISTING_FILE = $(wildcard $(FILE))
all:
@if [ "$(EXISTING_FILE)" != "" ]; then \
echo "File $(FILE) exists."; \
else \
echo "File $(FILE) does not exist."; \
fi
运行示例
同样,运行 make
,如果 myfile.txt
存在,您将得到:
File myfile.txt exists.
如果文件不存在,则会得到:
File myfile.txt does not exist.
总结
在 Makefile 中,可以使用 shell
命令结合 test
或 wildcard
函数来判断文件的存在性。这两种方法都能有效地帮助您在构建过程中进行条件判断,从而根据文件的存在与否进行不同的操作。选择适合您需求的方式即可。