Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kalj/1c85df4a9ba2f6de78f3bcce658f329c to your computer and use it in GitHub Desktop.
Save kalj/1c85df4a9ba2f6de78f3bcce658f329c to your computer and use it in GitHub Desktop.
# Add to ~/.bashrc
# call load_msenv [year] from a shell to load the enviroment
function load_msenv() {
local msversion_year=2019
if [ $# -gt 0 ]; then
msversion_year=$1
fi
case $msversion_year in
2017)
msversion_prod=15
;;
2019)
msversion_prod=16
;;
2022)
msversion_prod=17
;;
*)
>&2 printf "Invalid version year"
return 1
esac
local msversion_prod_p1=$(($msversion_prod+1))
local VSWHERE='C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe'
if [ ! -e "$VSWHERE" ]; then
>&2 printf "vswhere is nowhere to be found"
return 1
fi
local installPath=$("$VSWHERE" -products '*' -version "[$msversion_prod,$msversion_prod_p1)" -property installationPath)
local vcvarsall="${installPath}\\VC\\Auxiliary\\Build\\vcvarsall.bat"
local msenv="$HOME/.msenv_${msversion_year}_bash"
if [ ! -f "$msenv" ]; then
local msenvbatch="__print_ms_env.bat"
echo "@echo off" > "$msenvbatch"
echo "call \"${vcvarsall}\" x64" >> "$msenvbatch"
echo "set" >> "$msenvbatch"
cmd "//C $msenvbatch" > "$msenv.tmp"
rm -f "$msenvbatch"
local mspath="$(grep -E '^PATH=' "$msenv.tmp" | \
sed \
-e 's/.*=\(.*\)/\1/g' \
-e 's/\([a-zA-Z]\):[\\\/]/\/\1\//g' \
-e 's/\\/\//g' \
-e 's/;\//:\//g')"
echo "export PATH=\"${mspath}:\$PATH\"" > "$msenv"
# Don't mess with CL compilation env
grep -E '^(INCLUDE|LIB|LIBPATH)=' "$msenv.tmp" | \
sed \
-e 's/\(.*\)=\(.*\)/export \1="\2"/g' \
>> "$msenv"
rm -f "$msenv.tmp"
fi
source "$msenv"
}
export -f load_msenv
@kalj
Copy link
Author

kalj commented Jan 24, 2023

@mducle I noticed that too. Fixed now.

@kalj
Copy link
Author

kalj commented Jan 24, 2023

Just reviewed it now to not overwrite a previously set PATH; new version prepends the VS stuff to the existing path.

@reidrivenburgh
Copy link

I use git bash and wanted to give ninja a try, so this is very helpful, thanks!

@apodtele
Copy link

Thanks a lot!

I used to just alias MSBuild.exe, which works without any environment setup. Now I can run the compiler standalone too.

It would be nice to preserve the banner:

[vcvarsall.bat] Environment initialized for: 'x64'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment