使用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中,间接设置编译环境:
  1. # Define paths
  2. $vsDevCmd = "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat"
  3. $tempEnvFile = "$env:TEMP\env_vars.txt"

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

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

  8. # Import environment variables into PowerShell
  9. Get-Content $tempEnvFile | ForEach-Object {
  10. if ($_ -match "^(.*?)=(.*)$") {
  11. $name = $matches[1]
  12. $value = $matches[2]
  13. if ($name -eq "PATH") {
  14. # Append to PATH without overwriting
  15. $env:PATH = "$env:PATH;$value"
  16. } else {
  17. # Set other environment variables
  18. Set-Item -Path "env:$name" -Value $value
  19. }
  20. }
  21. }

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

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