4
votes

I'm writing a batch file to run some builds using Visual C++. I would like to "undo" the vsvars32.bat/vcvarsXX.bat changes at the end of the script so that I leave the environment unchanged from before the script ran.

Example 1 - using vsvars32.bat

call %VS100COMNTOOLS%vsvars32.bat
devenv myProject.sln /Build "Debug|Win32"
:: Now undo vsvars32.bat

Example 2 - using vcvars32.bat and vcvars64.bat

<path to VC bin>vcvars32.bat
:: cmd line build calls for 32 bit application
:: Now undo vcvars32.bat

<path to VC bin>amd64\vcvars64.bat
:: cmd line build calls for 64 bit application
:: Now undo vcvars64.bat

Any suggestions?

2

2 Answers

10
votes

The solution is simple - SETLOCAL coupled with ENDLOCAL. Type HELP SETLOCAL or HELP ENDLOCAL to get more info on usage.

Example 1:

setlocal
call %VS100COMNTOOLS%vsvars32.bat
devenv myProject.sln /Build "Debug|Win32"
endlocal

Example 2:

setlocal
<path to VC bin>vcvars32.bat
:: cmd line build calls for 32 bit application
endlocal

setlocal    
<path to VC bin>amd64\vcvars64.bat
:: cmd line build calls for 64 bit application
endlocal
1
votes

It would be simpler if your build.bat will be called by:

cmd.exe /c build.bat

This will:

  1. Create child process with copy of current environment.
  2. Modify this environment.
  3. Run build in modified child environment.
  4. discard child environment on process exit.

So nothing will change in current environment, and cleanup will be not necessary.