create cmd shortcut setting up environment

If you ever installed software like Visual Studio or Qt, you will find some cmd shortcuts in the start menu. For example, for VS, there are several cmd shortcuts in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2017\Visual Studio Tools\VC like “x86 Native Tools Command Prompt for VS 2017.lnk”. Double-clicking these cmd shortcuts not only brings you a cmd window where you can run build commands, but also sets up environment variables in the cmd so you do not need to set the environment variables manually, and those environment variables are vital for the execution of the build commands. How can it be possible?

A shortcut file(i.e., a .lnk file) contains not only the target file name, but also other meta information about the target file. In fact, the .lnk file has a binary file format. Usually, when you open a .lnk file, you are opening the target file. But you can use the following methods to open the shortcut file itself instead of the target file:

  • drag-drop the shortcut to notepad
  • rename the .lnk suffix to another non-existed suffix and open the renamed file in text editor
  • run “type xxx.lnk” to see the content of the shortcut file
  • use third-party tools such HxD Hex Editor

Either way, you can find the displayed content is almost unreadable because it is of binary format. Typically, you edit a shortcut not by an text editor but by right-clicking on the shortcut and selecting “properties” menu item, where you can change the target, start-in directory, run window, shortcut key, and comment.

To create a shortcut to cmd and set up environment variables for the cmd, right-click on empty area in Explorer or desktop, click New/Shortcut, then fill the location of target(%SystemRoot%\system32\cmd.exe /E:ON /V:ON /k C:\myvar.cmd) and a name(such as mycmd) for the shortcut. You can see the target program is the cmd command in system directory. But this time, the target application has a parameter c:\myvar.cmd.    c:\myvar.cmd is an ordinary .bat file which will be executed by cmd. myvar.cmd is responsible for setting up environment variables for the cmd:

CALL "C:\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" x64
SET _ROOT=C:\qt-src
SET PATH=%_ROOT%\qtbase\bin;%PATH%

Here, we set up the environment variables to build qt from source.


Posted in

Leave a Reply