Run Swift on Windows 11 in 2021
Steps:
1 — Install Visual Studio 2019 (or latest version that includes a “x64 Native Tools Command Prompt for VS 20XX” shortcut or the script called “C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat”): https://visualstudio.microsoft.com/downloads/
2 —Download and install Swift Toolchain for Windows 10 (works for W11 too): https://www.swift.org/download/
3 — Add a system variable named SDKROOT
with value “C:\Library\Developer\Platforms\Windows.platform\Developer\SDKs\Windows.sdk”
4 — Create your swift file with some code.
5 — Run the shortcut x64 Native Tools Command Prompt for VS 2019
located in “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\VC”. This will open a terminal in which we will be able to compile Swift. Do the following inside this terminal, otherwise you might get some nasty errors.
6 — Navigate to your swift file location. Create a “bin” folder and a “src” folder. Move your swift file to “src”. Then create this Makefile:
build: # SDKROOT: C:\Library\Developer\Platforms\Windows.platform\Developer\SDKs\Windows.sdk swiftc -sdk %SDKROOT% -resource-dir %SDKROOT%\usr\lib\swift -I %SDKROOT%\usr\lib\swift -L %SDKROOT%\usr\lib\swift\windows -emit-executable -o bin/main.exe src/main.swiftrun: bin\main.exe
7 — Now build it using nmake build
, if everything is OK a “main.exe” file will be generated inside the “bin” folder. Now you can run it by doing nmake run
. (nmake is a windows tool included with visual studio)