Compile Swift code to native executable for Linux

2020-07-16 02:44发布

问题:

I've installed Swift lang for Linux (Ubuntu) and it works fine. For example:

print("Hello World")

To run it:

./swift hi.swift

My question is, is it possible to generate a native executable code for it? How?

回答1:

Listing the executable files in the Swift directory, it has swiftc. It generates a native executable binary by command:

swiftc hi.swift -o hi
./hi


回答2:

In addition to swiftc, one can also generate native executables by using the Swift build system, which is described at

https://swift.org/getting-started/#using-the-build-system

Using the build system, one can easily build native executables from multiple source files, while swiftc is a convenient way to build an executable from a single source file.

Please note that you also need to install Clang if you want to create native executables with Swift. Clang is not needed to run the swift command interactively or to run a .swift file. Interestingly, installing GCC (including g++) and creating symlink clang++ to g++ does allow swiftrc to build an executable. This also enables swift build to work. At least it is true for very simple programs. However, this is not a "blessed" way. Apple docs at swift.org say that Clang is needed.



标签: linux swift