Friday, June 19, 2015

Static and Dynamic link for Swift Compiler

Swift compiler can be used to compile command line tool under Mac OSX. This is an example and how-to use swift compile and use the compiled module as immediate mode under Mac
http://github.com/practicalswift/Pythonic.swift
The above link has instruction to create the dynamic library libPythonic.dylib

After that, here is how to create the additional static library in swift compiler under Mac
Makefile    Select all
cd Pythonic.swift/src/
xcrun -sdk macosx swiftc -parse-as-library -module-name Pythonic -c Pythonic.swift Pythonic.*.swift
ar rvs libPythonic_static.a Pythonic*.o


And this is how to compile as command line tool and link against the static library as below
compile    Select all
mkdir -p my-pythonic-app cd my-pythonic-app/ cp ../Pythonic.swiftdoc ../Pythonic.swiftmodule ../libPythonic_static.a ../libPythonic.dylib . cat << EOF > my_pythonic_app.swift #!/usr/bin/env xcrun swift -I . import Pythonic assert(" hello ".strip() == "hello") println("This feels really.. Pythonic!") EOF xcrun swiftc -I. -L. -lPythonic_static -sdk $(xcrun --show-sdk-path --sdk macosx) my_pythonic_app.swift -o myapp1 ./myapp1
Note: If there is error __swift_FORCE_LOAD_$_swiftFoundation in linking static library try adding -Xlinker -all_load

To compile as command line tool by linking the dynamic library, use this Terminal command (please make sure that the dynamic library file libPythonic.dylib is copied to the current folder).
xcrun swiftc -I. -L. -module-link-name Pythonic -Xlinker -rpath -Xlinker "." -sdk $(xcrun --show-sdk-path --sdk macosx) my_pythonic_app.swift -o myapp2

Then compare the file size of myapp1 and myapp2 in order to verify the difference in linking methods.



No comments: