Swift on OS X compiling for Linux?
Asked Answered
S

2

16

I'm confused by the build process for Swift on other platforms.

Does Swift allow me to build a Linux project on OS X, or do I need to use Swift specifically on Linux to to build anything I plan on using there?

I looked at the documentation, but it's not really clear on this topic...

Sordino answered 27/1, 2016 at 15:30 Comment(1)
I built a docker container to help with the build process. You can install docker, launch the docker-cli, cd into your project directory and issue this command "docker run -it -v $(PWD):/swiftsource saltzmanjoelh/swiftubuntu /bin/bash". This will fire up the Linux container to let you build Swift on linux. Once the container has started, just "cd /swiftsource && swift build"Froufrou
S
10

A pure Swift application which is not importing any framework can now be compiled for iOS, OS X and for Linux.

You will generate different executables, because it's different platforms, but the code source can be the same, it just has to be compiled for the respective platform.

The difference is when you import frameworks.

If you import UIKit to make an iOS application, obviously you won't be able to compile this on Linux, because Linux doesn't have those iOS UIKit libraries, they're only available on a Mac via Xcode.

If you import Cocoa to make an OS X application, the same logic applies, it works only for OS X.

The same way, you can make Swift code that only works on Linux if you import specific Linux libraries, like Glibc, that won't work on the Mac.

Etc, etc.

What you need to remember is that the programming language isn't that relevant when it comes to make applications for a platform, it's the frameworks and libraries that you're linked to that are decisive.

Different Swift versions come with different compilers (different toolchains, actually) so to answer directly, no you can't compile for Linux Swift with the normal OS X Swift compiler, you have to use the Swift.org's one.

Summit answered 27/1, 2016 at 15:40 Comment(0)
H
6

The Swift Package Manager got custom toolchain support via PR-1098 end of April 2017.

This allows you to setup cross compiler toolchains (macOS to Ubuntu, even the reverse). The SwiftPM repo contains an example script which sets up a Intel-macOS => Intel-Ubuntu toolchain.

As Eric says, you can of course only use frameworks available on the target platform. But yes, you can now build a Linux Swift project on macOS. (as mentioned by joels in the comment you can also do this via Docker very easily)

Related: (Cross-)Compiling Swift for Raspberry PI

Update 2021-10-19: There are ready-made cross compilers available as a Homebrew tap: SPMDestinations

Hypertonic answered 16/5, 2017 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.