使用MSVC编译C文件
使用MSVC编译C文件
#msvc #windows #c #cpp
在MSYS2中,你可以使用GNU工具链来编译C代码。然而,使用MSVC进行比较可能会更加繁琐。
在开始菜单中,搜索Developer Command Prompt for VS来找到类似Developer Command Prompt for VS 2022的快捷方式。这个快捷方式运行一个批处理脚本来设置编译环境:%comspec% /k "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat"。然而,这只能作为批处理文件使用。在Fish shell中,cmd /kcmd /c都会退出Fish并切换到cmd,这有些不便。
以下PowerShell脚本运行批处理文件将环境变量存储到临时文件中,然后将其导入到PowerShell中,间接设置编译环境:
# Define paths
$vsDevCmd = "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat"
$tempEnvFile = "$env:TEMP\env_vars.txt"

# Create output directory
New-Item -ItemType Directory -Force -Path .\dist

# Run VsDevCmd.bat and capture environment variables
cmd.exe /c "`"$vsDevCmd`" -arch=x86 && set > $tempEnvFile"

# Import environment variables into PowerShell
Get-Content $tempEnvFile | ForEach-Object {
if ($_ -match "^(.*?)=(.*)$") {
$name = $matches[1]
$value = $matches[2]
if ($name -eq "PATH") {
# Append to PATH without overwriting
$env:PATH = "$env:PATH;$value"
} else {
# Set other environment variables
Set-Item -Path "env:$name" -Value $value
}
}
}

# Clean up temporary file
Remove-Item $tempEnvFile -ErrorAction SilentlyContinue

# Run cl.exe
cl /nologo .\c\main.c /O2 /Fo.\dist\ /Fe.\dist\msvc.exe /link /nologo /LTCG /OPT:REF /OPT:ICF
这允许你使用PowerShell通过MSVC编译C项目:
powershell -c "./build-msvc.ps1"
Aa