Running Ninja in Windows PowerShell

I’ve been on a journey recently of trying to get nvim, cmake, msvc, and ninja to all play nicely together, while trying to keep build scripts and configurations cross platform.

So here’s how I make it so that I can throw open any wt terminal and immediately run build commands without having to do any manual setup each time. (This post is for if my drives ever blow up again and I can’t remember how I did all of it).

First step is to create a .bat script that finds our visual studio install, and then prints out all the environment variables that we want:

@echo off
for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do (
  call "%%i\VC\Auxiliary\Build\vcvars64.bat"
)

I threw this into C:\scripts\vcenv.bat, but you can put it wherever you want, just make sure to update the next script with that new location.

Then we need to set a profile for PowerShell so that it runs that batch script on startup, You can find where to put the config file by typing $env:PROFILE into command prompt, and it should spit out the path and file name for where to put this:

cmd.exe /c "call `"C:\scripts\vsenv.bat`" && set > %temp%\vcvars.txt"
Get-Content "$env:temp\vcvars.txt" | foreach-object {
    if ($_ -match "^(.*?)=(.*)$" -and $matches[1] -notin @("VCPKG_ROOT")) {
        Set-Content "env:\$($matches[1])" $matches[2]
    }
}
Remove-Item "$env:temp\vcvars.txt"

This calls that .bat file from before, stores those env vars in a temp file, then we locally set those env vars from that file before deleting it. You can probably remove -and $matches[1] -notin @("VCPKG_ROOT") if you want, I have that in there because I have VCPKG_ROOT manually set globally and I don’t want visual studio to override that with it’s internal version.

This could probably be simplified into a single script if I wasn’t lazy, but ehh, it works.

After all that, CONGRATS, powershell now takes a second longer to open and you should see this message meaning you’re ready to go:

Generators such as cmake should be able to find msvc and use it for generators like Ninja, freeing us from the curse of always needing to build from an intermediate visual studio project on windows.

Liked it? Take a second to support WireWhiz on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.