Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile Swift script with static Swift core library

I would like to execute a compiled Swift script on a computer which doesn't have Swift installed. But it seems by default the Swift Compiler uses dynamically linked libraries. Is it possible to include these libraries statically?

Steps to reproduce using Docker:

user@host:~# docker run -it swiftdocker/swift
root@16974ad4edb1:/# swift --version
Swift version 3.0-dev (LLVM dffa09ffd8, Clang 9f0d189820, Swift 1c720b8f84)
Target: x86_64-unknown-linux-gnu
root@16974ad4edb1:/# echo 'print("Hello, world")' > helloworld.swift
root@16974ad4edb1:/# swiftc helloworld.swift
root@16974ad4edb1:/# ./helloworld
Hello, world
root@16974ad4edb1:/# exit
exit
user@host:~# docker cp 16974ad4edb1:/helloworld .
user@host:~# file helloworld
helloworld: ELF 64-bit LSB  executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=c4d42f6185b3d53ecf2dfb0c386263c17cb34675, not stripped
user@host:~# ./helloworld
./helloworld: error while loading shared libraries: libswiftCore.so: cannot open shared object file: No such file or directory
like image 334
Sony Avatar asked May 24 '16 09:05

Sony


People also ask

Does swift support static libraries?

Question: Can we create static frameworks using Swift? Answer: Finally, YES! (Xcode 9). CocoaPods announced the support of Swift Static Frameworks in 1.5.

Are Swift packages static or dynamic?

A library's product can be either statically or dynamically linked. It's recommended that you don't explicity declare the type of library, so Swift Package Manager can choose between static or dynamic linking based on the preference of the package's consumer.

What is a static library in Swift?

It's nothing fancy, but a collection of compiled source code files to achieve a particular functionality. Let's say we have FileA. swift, FileB. swift & FileC. swift, then we can compile them & wrap them together to form a Static Library which will have an extension of .

What is a static library Xcode?

Static library - a unit of code linked at compile time, which does not change.


1 Answers

The argument -static-stdlib must be used:

swiftc -static-stdlib helloworld.swift

For swift build, pass it to -Xswiftc:

swift build -Xswiftc -static-stdlib

If you get an ICU dependency error, install it:

apt-get install libicu-dev
like image 154
Sony Avatar answered Sep 19 '22 15:09

Sony