The Swift ecosystem is actively developing outside of Apple platforms, and today it is quite comfortable to write in it under Windows using the Windows Subsystem for Linux (WSL2). It is worth considering that for assemblies under Linux/WSL, a lightweight version of Swift is available – without proprietary Apple frameworks (such as SwiftUI, UIKit, AppKit, CoreData, CoreML, ARKit, SpriteKit and other iOS/macOS-specific libraries), but for console utilities and the backend this is more than enough. In this post, we will walk through the process of preparing the environment and building the Swift compiler from source code inside WSL2 step by step (using Ubuntu/Debian as an example).
We update the list of packages and the system itself:
sudo apt update && sudo apt upgrade -y
Install the necessary dependencies for the build:
sudo apt install -y \
git cmake ninja-build clang python3 python3-pip \
libicu-dev libxml2-dev libcurl4-openssl-dev \
libedit-dev libsqlite3-dev swig libncurses5-dev \
pkg-config tzdata rsync
Install the compiler and linker (LLVM and LLD):
sudo apt install -y llvm lld
Clone the Swift repository with all dependencies:
git clone https://github.com/apple/swift.git
cd swift
utils/update-checkout --clone
Install `swiftly` and ready-made swift with swiftc
curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz && \
tar zxf swiftly-$(uname -m).tar.gz && \
./swiftly init --quiet-shell-followup && \
. "${SWIFTLY_HOME_DIR:-$HOME/.local/share/swiftly}/env.sh" && \
hash -r
Let’s start the build (this will take a long time):
utils/build-script \
--release-debuginfo \
--swift-darwin-supported-archs="x86_64" \
--llvm-targets-to-build="X86" \
--skip-build-benchmarks \
--skip-test-cmark \
--skip-test-swift \
--skip-ios \
--skip-tvos \
--skip-watchos \
--skip-build-libdispatch=false \
--skip-build-cmark=false \
--skip-build-foundation \
--skip-build-lldb \
--skip-build-xctest \
--skip-test-swift
After the build is complete, add the path to the compiler to PATH (specify your path to the build folder):
export PATH=/root/Sources/3rdparty/build/Ninja-RelWithDebInfoAssert/swift-linux-x86_64/bin/swiftc:$PATH
We check that the installed version of Swift is working:
swift --version
Create a test file and run it:
echo "print(\"Hello, World!\")" > hello.swift
swift hello.swift
You can also compile the binary and run it:
swiftc hello.swift
./hello
Sources
- Getting Started with Swift on Windows
- Swiftly (version control tool)
- Building Swift from source code