Windows下Make执行PowerShell的Remove-Item命令报错,如何忽略不存在文件?
跨平台 Makefile clean 目标解决方案
问题根源
Make 在 Windows 环境下默认使用 cmd.exe 执行命令,而非 PowerShell。直接在 Makefile 中写 Remove-Item 会导致 cmd 无法识别该命令,这就是你单独在 PowerShell 中运行正常,但 make clean 报错的核心原因。
解决方法
通过 Make 的条件判断,为 Windows 和 Linux 分别指定对应的删除命令:
- Windows 下显式调用 PowerShell 执行
Remove-Item - Linux 下使用标准的
rm命令
完整的 Makefile 示例:
clean: ifeq ($(OS),Windows_NT) # Windows 平台:调用 PowerShell 执行删除,忽略不存在文件的错误 powershell.exe -Command "Remove-Item -ErrorAction Ignore *.o" else # Linux 平台:使用 rm -f 忽略不存在文件的错误 rm -f *.o endif
扩展说明
- 如果需要删除多种类型文件(比如同时删
*.o和*.exe),可以修改 PowerShell 命令为:powershell.exe -Command "Remove-Item -ErrorAction Ignore *.o, *.exe" $(OS)是 Make 的内置变量,Windows 环境下会自动设为Windows_NT,Linux 环境下该变量为空,以此实现跨平台分支判断。
内容的提问来源于stack exchange,提问作者DunZek
相关产品推荐
相关产品推荐

