LoginSignup
46
44

More than 5 years have passed since last update.

コマンドラインでswiftモジュールを作成、リンクする

Posted at

Xcodeのtoolchainを使用して、コマンドラインでswiftモジュールを作成、リンクする方法

PATHを通す

まず、PATHを通しておく。Xcode6-Betaの場合は

$ export PATH=/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin:$PATH

swiftmoduleファイル作成

Hoge.swiftをモジュール名 Hoge でモジュール化する場合

$ swift -module-name Hoge -emit-module Hoge.swift

これで、Hoge.swiftmodule と Hoge.swiftdoc の2つのファイルが出来る。
これがあれば import Hoge が可能になるが、いざ実行してみるとシンボルが無いと言われてエラーになる。

ライブラリファイル作成

実行時に必要となるダイナミックリンクライブラリを作成する。

$ swift -module-name Hoge -emit-object Hoge.swift
$ libtool -L/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx -dynamic -lswift_stdlib_core -lc -o libHoge.dylib Hoge.o

これで、libHoge.dylib が出来る。
-Lに渡しているパスは、Xcode6-Beta の場合。
-lcは、 _memcpy, _memset のために必要。

以上でモジュール側の準備終了。

リンクする

sample.swiftファイル内で import Hoge していて、これをコンパイルしてコマンドにする場合は

$ swift -I . -L . -lHoge sample.swift

-I に渡すパスはHoge.swiftmoduleのある場所、-Lに渡すパスはlibHoge.dylibのある場所。

これで sample コマンドが作成され、実行可能となる。

$ ./sample

sample.swiftをコマンドにコンパイルせず、いきなり実行する場合は -i オプションをつければ良い。
こちらの方がよく使いそう。

$ swift -I . -L . -lHoge -i sample.swift

swiftファイルを渡さず、REPLモードで対話的に実行したい場合は

$ swift -I . -L . -lHoge -integrated-repl
Welcome to swift.  Type ':help' for assistance.
(swift) import Hoge
(swift) var x = Hoge() // など、後はお好きなように
46
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
44