You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让mingw32-make执行PowerShell命令并实现Makefile跨平台兼容

跨平台Makefile日期输出解决方案

问题根源

mingw32-make 默认调用 Windows 的 cmd.exe 执行命令,你写的 PowerShell 语法在 cmd 里会被当成普通字符串直接输出;同时 Makefile 中的 $ 会被解析为自身变量,无法直接传递给命令解释器。

解决代码示例

# 判断当前运行平台
ifeq ($(OS),Windows_NT)
    # Windows 平台:指定用 PowerShell 执行命令,注意转义$和引号
    DATE_CMD = powershell -Command "echo \"the date and time is: $$(Get-Date -format 'yyyy-MM-dd HH:mm:ss')\""
else
    # Linux 平台:用 Bash 执行命令,处理引号嵌套
    DATE_CMD = bash -c 'echo "the date and time is: $(date '\''+%Y-%m-%d %H:%M:%S'\'')"'
endif

# 定义输出日期的目标
show-date:
	$(DATE_CMD)

关键细节解析

  • 指定命令解释器:Windows 下必须显式调用 powershell -Command,让命令交给 PowerShell 处理,替代默认的 cmd。
  • 转义 $ 符号:Makefile 中要传递给 shell 的 $ 必须写成 $$,否则会被 Make 当作自身变量解析(比如 PowerShell 的 $(Get-Date) 要写成 $$(Get-Date))。
  • 引号嵌套处理:Windows 下用 \" 转义双引号,避免 cmd 拆分带空格的字符串;Linux 下用单引号包裹外层命令,内部单引号转义为 \'。

验证方式

  • Linux 环境执行 make show-date,通过 Bash 输出格式化日期;
  • Windows 环境执行 mingw32-make show-date,通过 PowerShell 输出对应格式的日期。

内容的提问来源于stack exchange,提问作者Aqo Cyrale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:42:10