Build Script with PowerShell

May 15 2024

build.bat

@echo off where /q "cl.exe" || ( call "C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Auxiliary\Build\vcvars64.bat" ) pushd %~dp0 powershell.exe Set-ExecutionPolicy Bypass -Scope Process -Force; .\build.ps1 %* popd

build.ps1

param( [switch] $step = $False, [switch] $debugRun = $False, [switch] $run = $False, [Parameter(ValueFromRemainingArguments)] [string[]] $runArgs = @() ) if (-Not (Get-Command "cl.exe" 2> $null)) { &{Import-Module "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"; Enter-VsDevShell 2f3753d6 -SkipAutomaticLocation -DevCmdArguments "-arch=x64 -host_arch=x64"} if (-Not (Get-Command "cl.exe" 2> $null)) { throw "No cl.exe found. Please run this from the MSVC x64 native tools command prompt." } } $PROGNAME = 'my_executable' $compileFiles = @( 'main.c' ) $clFlags = @( '/nologo', '/W3', '/WX', '/Z7', '/Zc:preprocessor', '/GS-', '/Gm-', '/Gs999999', '/I"..\stb"' ) $linkFlags = @( '/incremental:no', '/opt:icf', '/opt:ref', '/ignore:4099', ) if ($env:DEBUGGER) { $debugger = $env:DEBUGGER } else { $debugger = "..\..\raddebugger\build\raddbg.exe" } try { Push-Location $PSScriptRoot if (-Not (Test-Path "build")) { New-Item -Name "build" -Type Directory > $null } # Convert paths to absolute paths for($i = 0; $i -lt $compileFiles.Length; $i++) { $f = $compileFiles[$i] $compileFiles[$i] = Resolve-Path "src\$f" } Push-Location "build" # Clean up stale PDBs. See https://www.computerenhance.com/p/msvc-pdbs-are-filled-with-stale-debug Remove-Item "*.pdb" # DEBUG build $time = Measure-Command { cl.exe -D_DEBUG -D_CONSOLE -Od -Fe"$PROGNAME.debug.exe" $clFlags $compileFiles /link $linkFlags /subsystem:console | Out-Default } if ($LastExitCode -ne 0) { throw "Error(s) compiling DEBUG." } Write-Host ("DEBUG took {0:F2}s to compile." -f $time.TotalSeconds) # RELEASE build $time = Measure-Command { cl.exe -O2 -Fe"$PROGNAME.exe" $clFlags $compileFiles /link $linkFlags /subsystem:windows | Out-Default } if ($LastExitCode -ne 0) { throw "Error(s) compiling RELEASE." } Write-Host ("RELEASE took {0:F2}s to compile." -f $time.TotalSeconds) # Handle running/debugging if ($debugRun) { & "$debugger" -auto_run "$PROGNAME.debug.exe" } elseif ($step) { & "$debugger" -auto_step "$PROGNAME.debug.exe" } elseif ($run) { & ".\$PROGNAME.exe" } } finally { Pop-Location Pop-Location }

Call the script like so: build -debugRun arg1 arg2 etc